<?php
function get_supplier_goods_list(){
    $result = get_filter();
    if ($result === false)
    {
        /* 初始化分页参数 */
        $filter = array();
        $filter['sort_by']    = empty($_REQUEST['sort_by']) ? 'supplier_goods_id' : trim($_REQUEST['sort_by']);
        $filter['sort_order']       = empty($_REQUEST['sort_order']) ? 'DESC' : trim($_REQUEST['sort_order']);
        $filter['id']               = empty($_REQUEST['id']) ? 0 : intval($_REQUEST['id']);
        $filter['cat_id']           = empty($_REQUEST['cat_id']) ? 0 : intval($_REQUEST['cat_id']);
        $filter['brand_id']         = empty($_REQUEST['brand_id']) ? 0 : intval($_REQUEST['brand_id']);
        $filter['keyword']          = empty($_REQUEST['keyword']) ? '' : trim($_REQUEST['keyword']);
        
        if ($_REQUEST['is_ajax'] == 1)
        {
            $filter['keyword'] = json_str_iconv($filter['keyword']);
        }
        
        $ext_sql = " WHERE sg.is_open=1 AND sg.supplier_id='$filter[id]'";
		$ext_sql .= $filter['cat_id'] > 0 ? " AND " . get_children($filter['cat_id']) : '';
		
        /* 品牌 */
        if ($filter['brand_id'])
        {
            $ext_sql .= " AND g.brand_id='$filter[brand_id]'";
        }   

        /* 关键字 */
        if (!empty($filter['keyword']))
        { 
			$filter['keyword'] = urldecode($filter['keyword']);
            $ext_sql .= " AND (g.goods_sn LIKE '%" . mysql_like_quote($filter['keyword']) . "%' OR g.goods_name LIKE '%" . mysql_like_quote($filter['keyword']) . "%')";
        }	

        /* 查询记录总数，计算分页数 */
        $sql = "SELECT COUNT(*) FROM " . $GLOBALS['os']->table('supplier_goods') . " sg LEFT JOIN " . 
               $GLOBALS['os']->table('goods') . " g ON sg.goods_id=g.goods_id " . $ext_sql;
        $filter['record_count'] = $GLOBALS['db']->getOne($sql);
        $filter['page_size']    = $filter['record_count'];
        $filter['page_count']   = 1;
        $filter['start']        = 0;

        /* 查询记录 */
        $sql = "SELECT g.goods_id,g.goods_name,g.goods_sn,sg.purchase_price,sg.goods_brief,sg.is_open " . 
               "FROM " . $GLOBALS['os']->table('supplier_goods') . " sg JOIN " . $GLOBALS['os']->table('goods') . 
               " g ON sg.goods_id=g.goods_id " . $ext_sql . " ORDER BY $filter[sort_by] $filter[sort_order]";
        set_filter($filter, $sql);
    }
    else
    {
        $sql    = $result['sql'];
        $filter = $result['filter'];
    }
    $res = $GLOBALS['db']->selectLimit($sql, $filter['page_size'], $filter['start']);

    $goods_list   = array();
	$goods_colors = array();
	$goods_sizes  = array();
	
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        $goods_list[$row['goods_id']] = $row;
    }
    
	$c_sql  = "SELECT gc.goods_id, c.color_id, c.color_code, c.color_name FROM " . $GLOBALS['os']->table('goods_color') . " gc JOIN " . 
	        $GLOBALS['os']->table('color') . " c ON gc.color_id=c.color_id WHERE " . db_create_in(array_keys($goods_list), 'gc.goods_id');
	$c_res = $GLOBALS['db']->query($c_sql);
	while ($c_row = $GLOBALS['db']->fetchRow($c_res)){
		$goods_colors[$c_row['goods_id']][$c_row['color_id']]['color_id']   = $c_row['color_id'];
		$goods_colors[$c_row['goods_id']][$c_row['color_id']]['color_code'] = $c_row['color_code'];
		$goods_colors[$c_row['goods_id']][$c_row['color_id']]['color_name'] = $c_row['color_name'];
	}
	
	$s_sql  = "SELECT gs.goods_id, s.size_id, s.size_code, s.size_name FROM " . $GLOBALS['os']->table('goods_size') . " gs JOIN " . 
	        $GLOBALS['os']->table('size') . " s ON gs.size_id=s.size_id WHERE " . db_create_in(array_keys($goods_list), 'gs.goods_id');
	$s_res = $GLOBALS['db']->query($s_sql);
	while ($s_row = $GLOBALS['db']->fetchRow($s_res)){
		$goods_sizes[$s_row['goods_id']][$s_row['size_id']]['size_id']   = $s_row['size_id'];
		$goods_sizes[$s_row['goods_id']][$s_row['size_id']]['size_code'] = $s_row['size_code'];
		$goods_sizes[$s_row['goods_id']][$s_row['size_id']]['size_name'] = $s_row['size_name'];		
	}
    $goods_specs = array();
    foreach($goods_list as $goods_id=>$g){
    	if(!empty($goods_colors[$goods_id]) && !empty($goods_sizes[$goods_id])){
    		foreach ($goods_colors[$goods_id] as $color_id=>$gc){
    			$goods_specs[$goods_id][$color_id] = $gc;
    			foreach($goods_sizes[$goods_id] as $size_id=>$gs){ 
                       $goods_specs[$goods_id][$color_id]['size_specs'][$size_id] = $gs;
    			}
    		}
    	}
    }
    $arr = array();
    foreach($goods_list as $g){
    	$g['specs'] = !empty($goods_specs[$g['goods_id']]) ? $goods_specs[$g['goods_id']] : 0;
    	$g['short_goods_name']  = sub_str($g['goods_name'], 20);
    	$arr[] = $g;
    }
    return array('operate_goods' => $arr, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);
}


function edit_scm_order_goods($str_type, $order_id, $supplier_id, $haystack=array(), $supply_discount){
	static    $arr_type  =  array('purchase', 'enter', 'return');
	if(!in_array($str_type, $arr_type)) return false;
	
	$goods_list   = array();
	$goods_colors = array();
	$goods_sizes  = array();

	$arr_goods = array_keys($haystack);
    	
	$sql = "SELECT g.goods_id,g.shop_price FROM " . $GLOBALS['os']->table('supplier_goods') . " sg LEFT JOIN " .  
	       $GLOBALS['os']->table('goods') . " g ON sg.goods_id=g.goods_id WHERE g.is_delete=0 AND sg.is_open=1" . 
	       " AND sg.supplier_id=" . intval($supplier_id) . " AND " . db_create_in($arr_goods, 'sg.goods_id');
	$res = $GLOBALS['db']->query($sql);
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        $goods_list[$row['goods_id']] = $row;
    }
    
	$c_sql  = "SELECT gc.goods_id, c.color_id FROM " . $GLOBALS['os']->table('goods_color') . " gc JOIN " . $GLOBALS['os']->table('color') . 
	          " c ON gc.color_id=c.color_id WHERE " . db_create_in(array_keys($goods_list), 'gc.goods_id');
	$c_res = $GLOBALS['db']->query($c_sql);
	while ($c_row = $GLOBALS['db']->fetchRow($c_res)){
		$goods_colors[$c_row['goods_id']][$c_row['color_id']]   = $c_row['color_id'];
	}
	
	$s_sql  = "SELECT gs.goods_id, s.size_id FROM " . $GLOBALS['os']->table('goods_size') . " gs JOIN " . $GLOBALS['os']->table('size') . 
	          " s ON gs.size_id=s.size_id WHERE " . db_create_in(array_keys($goods_list), 'gs.goods_id');
	$s_res = $GLOBALS['db']->query($s_sql);
	while ($s_row = $GLOBALS['db']->fetchRow($s_res)){
		$goods_sizes[$s_row['goods_id']][$s_row['size_id']]   = $s_row['size_id'];	
	}

	foreach ($goods_list as $goods_id=>$g){
		if(!empty($haystack[$goods_id])){
		foreach ($haystack[$goods_id] as $color_id=>$arr_sizes){
			if(!empty($goods_colors[$goods_id][$color_id])){
			foreach ($arr_sizes as $size_id=>$num){
				 if(!empty($goods_sizes[$goods_id][$size_id]) && (is_numeric($num) && $num>0)){
				 	$norm_price    = floatval($g['shop_price']);
				 	$actual_price  = floatval($norm_price*$supply_discount);
				 	$norm_amount   = floatval($norm_price*$num);
				 	$actual_amount = floatval($actual_price*$num);
				 	$sql = "INSERT INTO " . $GLOBALS['os']->table('scm_'.$str_type.'_goods') . " (order_id,goods_id,color_id,size_id," . 
				 	       "goods_number,norm_price,discount,actual_price,norm_amount,actual_amount) VALUES('$order_id','$goods_id'," . 
				 	       "'$color_id','$size_id','$num','$norm_price','$supply_discount','$actual_price','$norm_amount','$actual_amount'" . 
				 	       ") ON DUPLICATE KEY UPDATE goods_number=goods_number+$num";
				 	$GLOBALS['db']->query($sql);
				 }
			}
			}
		}			
		}
	}
	$GLOBALS['db']->query("UPDATE " . $GLOBALS['os']->table('scm_'.$str_type.'_goods') . " SET norm_price='$norm_price',
	                      discount='$supply_discount',actual_price='$actual_price',norm_amount=goods_number*$norm_price,
	                      actual_amount=goods_number*$actual_price WHERE order_id='$order_id' AND goods_id='$goods_id'"); 
}

function edit_scm_depot_order_goods($str_type, $order_id, $haystack=array()){
	static    $arr_type  =  array('check', 'rectify');
	if(!in_array($str_type, $arr_type)) return false;
	
	$goods_list   = array();
	$goods_colors = array();
	$goods_sizes  = array();

	$arr_goods = array_keys($haystack);
	 	
	$sql = "SELECT goods_id,shop_price FROM " . $GLOBALS['os']->table('goods') . " WHERE is_delete=0 AND " . 
	       db_create_in($arr_goods, 'goods_id');
	$res = $GLOBALS['db']->query($sql);
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        $goods_list[$row['goods_id']] = $row;
    }
    
	$c_sql  = "SELECT gc.goods_id,c.color_id FROM " . $GLOBALS['os']->table('goods_color') . " gc JOIN " . $GLOBALS['os']->table('color') . 
	          " c ON gc.color_id=c.color_id WHERE " . db_create_in(array_keys($goods_list), 'gc.goods_id');
	$c_res = $GLOBALS['db']->query($c_sql);
	while ($c_row = $GLOBALS['db']->fetchRow($c_res)){
		$goods_colors[$c_row['goods_id']][$c_row['color_id']]   = $c_row['color_id'];
	}
	
	$s_sql  = "SELECT gs.goods_id,s.size_id FROM " . $GLOBALS['os']->table('goods_size') . " gs JOIN " . $GLOBALS['os']->table('size') . 
	          " s ON gs.size_id=s.size_id WHERE " . db_create_in(array_keys($goods_list), 'gs.goods_id');
	$s_res = $GLOBALS['db']->query($s_sql);
	while ($s_row = $GLOBALS['db']->fetchRow($s_res)){
		$goods_sizes[$s_row['goods_id']][$s_row['size_id']]   = $s_row['size_id'];	
	}

	foreach ($goods_list as $goods_id=>$g){
		if(!empty($haystack[$goods_id])){
		foreach ($haystack[$goods_id] as $color_id=>$arr_sizes){
			if(!empty($goods_colors[$goods_id][$color_id])){
			foreach ($arr_sizes as $size_id=>$num){
				 if(!empty($goods_sizes[$goods_id][$size_id]) && (is_numeric($num) && $num>0)){
				 	$actual_price  = floatval($g['shop_price']);
				 	$actual_amount = floatval($actual_price*$num);    
				 	if($str_type=='rectify'){
							$sql_in = "SELECT goods_number_actual FROM " . $GLOBALS['os']->table('goods_inventory') . 
							          " WHERE goods_id='$goods_id' AND color_id='$color_id' AND size_id='$size_id'";
							$inventory_num = $GLOBALS['db']->getOne($sql_in);	
							$inventory_num = is_numeric($inventory_num) ? intval($inventory_num) : 0;
							$loss_num      = intval($num-$inventory_num);
					    	$sql_ls = "INSERT INTO " . $GLOBALS['os']->table('scm_'.$str_type.'_goods') . " (order_id, goods_id, color_id," . 
					    	          " size_id, goods_number, goods_number_inventory, goods_number_loss, actual_price, actual_amount," . 
					    	          " loss_amount) VALUES ('$order_id', '$goods_id', '$color_id', '$size_id', '$num', '$inventory_num'," . 
					    	          " '$loss_num', '$actual_price', '$actual_amount', $actual_price*$loss_num) ON DUPLICATE KEY UPDATE " . 
					    	          " goods_number=goods_number+$num, goods_number_inventory='$inventory_num', goods_number_loss=goods_number_loss+$num" . 
					    	          ", actual_price='$actual_price', actual_amount=goods_number*$actual_price, loss_amount=actual_price*goods_number_loss";  
					    	$GLOBALS['db']->query($sql_ls);					 		
				 	}else{
						 	$sql = "INSERT INTO " . $GLOBALS['os']->table('scm_'.$str_type.'_goods') . " (order_id,goods_id,color_id," . 
						 	       "size_id,goods_number,actual_price,actual_amount) VALUES('$order_id','$goods_id','$color_id','$size_id'," . 
						 	       "'$num','$actual_price','$actual_amount') ON DUPLICATE KEY UPDATE goods_number=goods_number+$num," . 
						 	       "actual_price='$actual_price',actual_amount=goods_number*$actual_price";
						 	$GLOBALS['db']->query($sql);				 		
				 	}				 	
				 }
			}
			}
		}			
		}
	}
}

function  update_scm_order_goods($str_type, $order_id, $haystack=array()){
	static    $arr_type  =  array('purchase', 'enter', 'return', 'check');
	if(!in_array($str_type, $arr_type)) return false;
	
    if (count($haystack['goods_numbers'])>0){   
    	foreach($haystack['goods_numbers'] as $key=>$val){  
    		 if(empty($val) || !is_numeric($val) || $val<=0) break;
    		 $goods_id = empty($haystack['goods_ids'][$key]) ? 0 : intval($haystack['goods_ids'][$key]);
    		 $color_id = empty($haystack['color_ids'][$key]) ? 0 : intval($haystack['color_ids'][$key]);
    		 $size_id  = empty($haystack['size_ids'][$key]) ? 0 : intval($haystack['size_ids'][$key]);
    		 
    		 $sql = "SELECT norm_price,discount,actual_price FROM " . $GLOBALS['os']->table('scm_'.$str_type.'_goods') . 
    		        " WHERE order_id='$order_id' AND goods_id='$goods_id' AND color_id='$color_id' AND size_id='$size_id'";
    		 $old_row = $GLOBALS['db']->getRow($sql);
    		 $norm_amount   = floatval($old_row['norm_price'] * $val);
		     $actual_price  = floatval($old_row['norm_price'] * $old_row['discount']);
		     $actual_amount = floatval($actual_price * $val);   
		 
		     $sql = 'UPDATE ' . $GLOBALS['os']->table('scm_'.$str_type.'_goods') . ' SET goods_number=' . intval($val) .  
		            ",norm_amount='$norm_amount',actual_price='$actual_price',actual_amount='$actual_amount' WHERE " . 
		            " order_id='$order_id' AND goods_id='$goods_id' AND color_id='$color_id' AND size_id='$size_id'";
		     $GLOBALS['db']->query($sql); 
    	}
    }
}

function  update_scm_depot_order_goods($str_type, $order_id, $haystack=array()){
	static    $arr_type  =  array('check', 'rectify');
	if(!in_array($str_type, $arr_type)) return false;
	
    if (count($haystack['goods_numbers'])>0){   
    	foreach($haystack['goods_numbers'] as $key=>$val){  
    		 if(empty($val) || !is_numeric($val) || $val<=0) break;
    		 $goods_id = empty($haystack['goods_ids'][$key]) ? 0 : intval($haystack['goods_ids'][$key]);
    		 $color_id = empty($haystack['color_ids'][$key]) ? 0 : intval($haystack['color_ids'][$key]);
    		 $size_id  = empty($haystack['size_ids'][$key]) ? 0 : intval($haystack['size_ids'][$key]);
    		 
    		 if($str_type=='rectify'){		 
				 $sql_in = "SELECT goods_number_actual FROM " . $GLOBALS['os']->table('goods_inventory') . 
				          " WHERE goods_id='$goods_id' AND color_id='$color_id' AND size_id='$size_id'";
				 $inventory_num = $GLOBALS['db']->getOne($sql_in);	
				 $inventory_num = is_numeric($inventory_num) ? intval($inventory_num) : 0;
				 $loss_num      = intval($val-$inventory_num);
		    	 $sql = "UPDATE " . $GLOBALS['os']->table('scm_'.$str_type.'_goods') . " SET goods_number='$val', " . 
		    	        "goods_number_inventory='$inventory_num', goods_number_loss='$loss_num', actual_amount=actual_price*$val," . 
		    	        " loss_amount=actual_price*$loss_num WHERE order_id='$order_id' AND goods_id='$goods_id' AND " . 
			            " color_id='$color_id' AND size_id='$size_id'";
		    	 $GLOBALS['db']->query($sql);
    		 }else{
			     $sql = "UPDATE " . $GLOBALS['os']->table('scm_'.$str_type.'_goods') . " SET goods_number='$val', " . 
			            "actual_amount=actual_price*$val WHERE order_id='$order_id' AND goods_id='$goods_id' AND " . 
			            " color_id='$color_id' AND size_id='$size_id'";
			     $GLOBALS['db']->query($sql);     		 	
    		 }
    	}
    }
}

function get_supplier_info($supplier_id){
    $sql = "SELECT * FROM " . $GLOBALS['os']->table('supplier') . " WHERE supplier_id=" . intval($supplier_id);
    $supplier = $GLOBALS['db']->getRow($sql); 
    return 	$supplier;
}

function create_tmp_scm_order($str_type, $haystack=array()){
	static    $arr_type  =  array('purchase', 'enter', 'return', 'check', 'rectify');
	if(!in_array($str_type, $arr_type)) return false; 
	$tb = sprintf("scm_%s_order", $str_type);
	
	$GLOBALS['db']->autoExecute($GLOBALS['os']->table($tb), $haystack);	

    return $GLOBALS['db']->insert_id();    	
}

function clear_tmp_scm_order($str_type){
	static    $arr_type  =  array('check', 'rectify');
	if(!in_array($str_type, $arr_type)) return false; 
	$tb = sprintf("scm_%s_order", $str_type);
	$order_ids = $GLOBALS['db']->getCol("SELECT order_id FROM " . $GLOBALS['os']->table($tb) . " WHERE is_temp=1");
    if (is_array($order_ids) && sizeof($order_ids)>0)
    {    
    	$res = $GLOBALS['db']->query("DELETE FROM " . $GLOBALS['os']->table($tb) . " WHERE is_temp=1 AND " . db_create_in($order_ids, 'order_id'));	
    	if($res==FALSE) return false;
    	$tb  = sprintf("scm_%s_goods", $str_type);
    	$res = $GLOBALS['db']->query("DELETE FROM " . $GLOBALS['os']->table($tb) . " WHERE " . db_create_in($order_ids, 'order_id'));	
    	if($res==FALSE) return false;	
    }    
    return true;    	
}

function fast_scm_order_ur($str_type){
 	static    $arr_type  =  array('purchase', 'enter', 'return', 'check', 'rectify');
	if(!in_array($str_type, $arr_type)) return false;  
	switch ($str_type){
		case 'purchase':
			$ur_here = '采购单';
			break;
		case 'enter':				
			$ur_here = '采购入库单';
			break;
		case 'return':				
			$ur_here = '采购退货单';
			break;
		case 'check':				
			$ur_here = '仓储盘点单';
			break;	
		case 'rectify':				
			$ur_here = '仓储调整单';
			break;						
	}
	return  $ur_here;	
}
/**
 * 取得进销存单据的状态
 * @param   string  $str_type           类型字符
 * @param   int     $status     		状态值
 * @return  array   单据的状态列表
 * @return  string  单据的状态
 */
function scm_order_status($str_type, $status=NULL){
	static 	  $haystack_sts;
	static    $arr_type         = array('purchase', 'enter', 'return', 'check', 'loss', 'rectify', 'balance');
	static    $arr_status       = array();
	$arr_status['purchase']     = array(0=>'待处理', 1=>'仓储审核已通过', 2=>'仓储审核未通过', 3=>'财务审核已通过', 4=>'财务审核未通过', 5=>'已生成入库单', 6=>'已完成', 7=>'已作废');
	$arr_status['enter']   		= array(0=>'待处理', 1=>'已验收',	2=>'已入库', 3=>'已结算', 4=>'已作废');
	$arr_status['return']  		= array(0=>'待处理', 1=>'已验收', 2=>'已出库', 3=>'已结算', 4=>'已作废');
	$arr_status['check']   		= array(0=>'待处理', 1=>'已确认', 2=>'已作废', 3=>'已盈亏');
	$arr_status['loss']    		= array(0=>'待处理', 1=>'已确认', 2=>'已作废', 3=>'已生成调整');
	$arr_status['rectify'] 		= array(0=>'待处理', 1=>'已确认', 2=>'已调整', 3=>'已回滚', 4=>'已作废', 5=>'已完成');
	$arr_status['balance'] 		= array(0=>'待处理', 1=>'已确认', 2=>'已付款', 3=>'已作废');
		
	if(!in_array($str_type, $arr_type)) return false; 	
    $haystack_sts = $arr_status[$str_type];
	if(is_numeric($status) && isset($haystack_sts[$status])){
		$haystack_sts = $haystack_sts[$status];
	}
	return $haystack_sts;
}

function update_scm_order($str_type, $order_id, $order)
{ 
	static    $arr_type  =  array('purchase', 'enter', 'return', 'check', 'loss', 'rectify', 'balance');
	if(!in_array($str_type, $arr_type)) return false; 
	$tb = sprintf("scm_%s_order", $str_type);	
    return $GLOBALS['db']->autoExecute($GLOBALS['os']->table($tb), $order, 
    							       'UPDATE', "order_id = '$order_id'");
}

function scm_order_action($str_type, $order_id)
{	
	static    $arr_type  =  array(0=>'purchase', 1=>'enter', 2=>'return', 3=>'check', 4=>'loss', 5=>'rectify', 6=>'balance');
	if(!in_array($str_type, $arr_type)) return false;
	while (list($ctype, $stype)=each($arr_type)) {
		if($stype==$str_type){
			break;
		}
	}
	$act_list = array();
	$sql = "SELECT * FROM " . $GLOBALS['os']->table('scm_order_action') . " WHERE ctype='$ctype' AND order_id='$order_id' ORDER BY log_time DESC";
	$res = $GLOBALS['db']->query($sql);
	while ($row = $GLOBALS['db']->fetchRow($res))
	{
		$row['order_status']    = scm_order_status($stype, $row['order_status']);
		$row['action_time']     = local_date($GLOBALS['_CFG']['time_format'], $row['log_time']);
		$act_list[] = $row;
	}	
	return $act_list;
}

function update_scm_order_action($str_type, $order_sn, $order_status, $note = '', $username = null){
	static    $arr_type  =  array(0=>'purchase', 1=>'enter', 2=>'return', 3=>'check', 4=>'loss', 5=>'rectify', 6=>'balance');
	if(!in_array($str_type, $arr_type)) return false;
	while (list($ctype, $stype)=each($arr_type)) {
		if($stype==$str_type){
			$tb = sprintf("scm_%s_order", $stype);
			break;
		}
	}	
    if (is_null($username))
    {
        $username = $_SESSION['admin_name'];
    }

    $sql = "INSERT INTO " . $GLOBALS['os']->table('scm_order_action') .
           " (ctype, order_id, action_user, order_status, action_note, log_time) " .
           "SELECT '$ctype', order_id, '$username', '$order_status', '$note', '" .
            gmtime() . "' FROM " . $GLOBALS['os']->table($tb) . " WHERE order_sn = '$order_sn'";            

    $GLOBALS['db']->query($sql);
}

function scm_order_amount($str_type, $order_id){
	static    $arr_type  =  array('purchase', 'enter', 'return', 'check', 'loss', 'rectify', 'balance');
	if(!in_array($str_type, $arr_type)) return false; 
	$tb = sprintf("scm_%s_goods", $str_type);
	$arr_tmp = array();
	$sql = "SELECT * FROM " . $GLOBALS['os']->table($tb) . " WHERE order_id=" . intval($order_id);
	$all_number  = 0;
	$all_amount   = 0.00;
	$res = $GLOBALS['db']->query($sql);
	while ($row = $GLOBALS['db']->fetchRow($res)){
		 $all_number 		+= 	intval($row['goods_number']);
		 $all_amount        +=  floatval($row['actual_price'] * $row['goods_number']);	
	}
	$arr_tmp['goods_number']  	= intval($all_number);
	$arr_tmp['order_amount']    = floatval(round($all_amount, 2));		
    return $arr_tmp;    
}

function create_scm_order_sn($str_type, $prefix='', $length=4)
{
	static    $arr_type  =  array('purchase', 'enter', 'check', 'loss', 'rectify', 'return', 'balance');
	if(!in_array($str_type, $arr_type)) return false;
	$tb = sprintf("scm_%s_order", $str_type);
    $sn = '';
    while (empty($sn))
    {
        $sn = empty($prefix) ? generate_rand($length) : ($prefix . generate_rand($length));
        if ($GLOBALS['db']->getOne("SELECT order_sn FROM ".$GLOBALS['os']->table($tb)." WHERE order_sn='$sn'"))
        {
            $sn = '';
        }
    }
    return $sn;	
}

function create_fast_order_sn($str_type, $length=4){
	static    $arr_type  =  array('purchase', 'enter', 'return', 'check', 'loss', 'rectify', 'balance');
	if(!in_array($str_type, $arr_type)) return false;
	switch ($str_type) {
		default:
			return false;
			break;	
		case 'purchase':
			$prefix = 'CG';
			break;
		case 'enter':
			$prefix = 'RK';
			break;	
		case 'return':		
			$prefix = 'TH';
            break;
		case 'check':		
			$prefix = 'PD';
            break;   
		case 'loss':		
			$prefix = 'YK';
            break;    
 		case 'rectify':		
			$prefix = 'TZ';
            break;           
		case 'balance':		
			$prefix = 'JS';
            break;          
	}
	return create_scm_order_sn($str_type, $prefix.date('Ymd'), $length);	
}

function get_fast_scm_order_info($str_type, $order_id){
	static    $arr_type  =  array('purchase', 'enter', 'return', 'check', 'rectify');
	if(!in_array($str_type, $arr_type)) return false;
	switch ($str_type) {
		default:
			return false;
			break;	
		case 'purchase':
			$order = scm_purchase_order_info($order_id); 
			break;
		case 'enter':
			$order = scm_enter_order_info($order_id); 
			break;	
		case 'return':		
			$order = scm_return_order_info($order_id); 
            break;
		case 'check':		
			$order = scm_check_order_info($order_id); 
            break;   
 		case 'rectify':		
			$order = scm_rectify_order_info($order_id); 
            break;                   
	}	
    if(empty($order))
	{
		return false;
	}
	return $order;
}

function alter_storage($str_type, $order_id, $is_plus=TRUE){
	static    $arr_type  =  array('enter', 'return', 'rectify');
	if(!in_array($str_type, $arr_type)) return false;
	$tb = sprintf("scm_%s_goods", $str_type);
	$fld = ($str_type=='rectify') ? 'goods_number_loss AS goods_number' : 'goods_number';
	$res = $GLOBALS['db']->query("SELECT goods_id,color_id,size_id,$fld FROM " . $GLOBALS['os']->table($tb) . 
								 " WHERE order_id=" . intval($order_id));
								 	
    if ($res === FALSE)
    {    
        return false;    	
    }
    
	$sign = ($is_plus!==FALSE)  ?  '+'  :  '-';
	while ($row=$GLOBALS['db']->fetchRow($res)) {
		$rectify_num = !empty($row['goods_number']) ? intval($row['goods_number']) : 0;
		$sql_in = "INSERT INTO " . $GLOBALS['os']->table('goods_inventory') . " (goods_id,color_id,size_id,goods_number_actual," . 
		          "goods_number_available) VALUES ($row[goods_id], $row[color_id], $row[size_id], 0" . $sign . $rectify_num . 
		          ", 0" . $sign . $rectify_num .")  ON DUPLICATE KEY UPDATE goods_number_actual=goods_number_actual" . 
		          $sign . $rectify_num . ",goods_number_available=goods_number_available" . $sign . $rectify_num;
    	$GLOBALS['db']->query($sql_in);  				
	}
	return true;
}

function scm_purchase_order_list()
{
    $result = get_filter();
    if ($result === false)
    {
        /* 初始化分页参数 */
        $filter = array();
        $filter['sort_by']    = empty($_REQUEST['sort_by']) ? 'order_id' : trim($_REQUEST['sort_by']);
        $filter['sort_order'] = empty($_REQUEST['sort_order']) ? 'DESC' : trim($_REQUEST['sort_order']);
        $filter['order_sn']   = empty($_REQUEST['order_sn']) ? '' : trim($_REQUEST['order_sn']);
        $filter['status']     = (!is_numeric($_REQUEST['status']) || $_REQUEST['status']<0) ? -1 : intval($_REQUEST['status']);
        if (!empty($_GET['is_ajax']) && $_GET['is_ajax'] == 1)
        {
            $_REQUEST['supplier_name'] = json_str_iconv($_REQUEST['supplier_name']);
        }
        $filter['supplier_name']       = empty($_REQUEST['supplier_name']) ? '' : trim($_REQUEST['supplier_name']); 
        $filter['start_add_time']      = empty($_REQUEST['start_add_time']) ? '' : (strpos($_REQUEST['start_add_time'], '-') > 0 ?  local_strtotime($_REQUEST['start_add_time']) : $_REQUEST['start_add_time']);
        $filter['end_add_time']        = empty($_REQUEST['end_add_time']) ? '' : (strpos($_REQUEST['end_add_time'], '-') > 0 ?  local_strtotime($_REQUEST['end_add_time']) : $_REQUEST['end_add_time']);	
        $filter['start_deliver_time']  = empty($_REQUEST['start_deliver_time']) ? '' : (strpos($_REQUEST['start_deliver_time'], '-') > 0 ?  local_strtotime($_REQUEST['start_deliver_time']) : $_REQUEST['start_deliver_time']);
        $filter['end_deliver_time']    = empty($_REQUEST['end_deliver_time']) ? '' : (strpos($_REQUEST['end_deliver_time'], '-') > 0 ?  local_strtotime($_REQUEST['end_deliver_time']) : $_REQUEST['end_deliver_time']);

        $where = 'WHERE 1 ';
        if ($filter['order_sn'])
        {
            $where .= " AND o.order_sn LIKE '%" . mysql_like_quote($filter['order_sn']) . "%'";
        }
        if($filter['status']>=0){
        	$where .= " AND o.order_status=$filter[status]";
        }
        if ($filter['supplier_name'])
        {
            $where .= " AND s.supplier_name LIKE '%" . mysql_like_quote($filter['supplier_name']) . "%'";
        }  
        if ($filter['start_add_time'])
        {
            $where .= " AND o.add_time >= '$filter[start_add_time]'";
        }
        if ($filter['end_add_time'])
        {
            $where .= " AND o.add_time <= '$filter[end_add_time]'";
        }
        if ($filter['start_deliver_time'])
        {
            $where .= " AND o.deliver_time >= '$filter[start_deliver_time]'";
        }
        if ($filter['end_deliver_time'])
        {
            $where .= " AND o.deliver_time <= '$filter[end_deliver_time]'";
        }                     
        /* 查询记录总数，计算分页数 */
   		$sql = "SELECT COUNT(*) FROM " . $GLOBALS['os']->table('scm_purchase_order') . " o LEFT JOIN " . 
   		       $GLOBALS['os']->table('supplier') . " s ON o.supplier_id=s.supplier_id " . $where;
        $filter['record_count'] = $GLOBALS['db']->getOne($sql);
        $filter = page_and_size($filter);

        /* 查询记录 */
        $sql = "SELECT o.*,s.supplier_name FROM " . $GLOBALS['os']->table('scm_purchase_order') . " o LEFT JOIN " . 
   		       $GLOBALS['os']->table('supplier') . " s ON o.supplier_id=s.supplier_id " . $where .
   		       " ORDER BY $filter[sort_by] $filter[sort_order]";
        set_filter($filter, $sql);
    }
    else
    {
        $sql    = $result['sql'];
        $filter = $result['filter'];
    }
    $res = $GLOBALS['db']->selectLimit($sql, $filter['page_size'], $filter['start']);

    $arr = array();
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
		$row['status']  				    = scm_order_status('purchase', $row['order_status']);
		$row['formated_discount']  		    = sprintf('%s', $row['discount']);
      	$row['formated_order_amount']	    = price_format(abs($row['order_amount']), false);
      	$row['formated_add_time']           = local_date('Y-m-d', $row['add_time']);
      	$row['formated_deliver_time']       = local_date('Y-m-d', $row['deliver_time']);
      	$row['short_supplier_name']         = sub_str($row['supplier_name'], 10);
        $arr[] = $row;
    }
    return array('item' => $arr, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);	
}

function scm_purchase_order_info($order_id, $order_sn = '')
{
    /* 计算订单各种费用之和的语句 */
    $order_id = intval($order_id);
    if ($order_id > 0)
    {
        $sql = "SELECT o.*,s.supplier_name,eo.order_sn enter_order_sn FROM " . $GLOBALS['os']->table('scm_purchase_order') . 
               " o LEFT JOIN " . $GLOBALS['os']->table('supplier') . " s ON o.supplier_id=s.supplier_id LEFT JOIN " . 
               $GLOBALS['os']->table('scm_enter_order') . " eo ON o.order_id=eo.purchase_order_id WHERE o.order_id = '$order_id'";	
    }
    else
    {
        $sql = "SELECT o.*,s.supplier_name,eo.order_sn enter_order_sn FROM " . $GLOBALS['os']->table('scm_purchase_order') . 
        	   " o LEFT JOIN " . $GLOBALS['os']->table('supplier') . " s ON o.supplier_id=s.supplier_id LEFT JOIN " . 		
               $GLOBALS['os']->table('scm_enter_order') . " eo ON o.order_id=eo.purchase_order_id WHERE o.order_sn = '$order_sn'";	
    }   
    $order = $GLOBALS['db']->getRow($sql);

    /* 格式化字段 */
    if ($order)
    {
    	$order['short_supplier_name']     = sub_str($order['supplier_name'], 10);
        $order['depot_name']              = ' 默认 ';
        $order['seat_name']               = ' 默认 ';
        $order['formated_discount']       = sprintf('%s' , $order['discount']);
     	$order['formated_add_time']       = local_date('Y-m-d', $order['add_time']); 
     	$order['formated_deliver_time']   = local_date('Y-m-d', $order['deliver_time']);       
        $order['formated_order_amount']   = price_format(abs($order['order_amount']), false);
		$order['status']                  = scm_order_status('purchase', $order['order_status']);
    }
    return $order;
}

function scm_order_goods($str_type, $order_id){
	static $arr_type  =  array('purchase', 'enter', 'check', 'loss', 'rectify', 'return', 'balance');
	$goods_list = array();
	$sql = "SELECT og.*,SUM(og.goods_number) subtotal_number,SUM(og.actual_amount) subtotal_amount,g.goods_name," . 
		   "g.goods_sn FROM " . $GLOBALS['os']->table('scm_'.$str_type.'_goods') . " og LEFT JOIN " . 
		   $GLOBALS['os']->table('goods') . " g ON og.goods_id=g.goods_id WHERE og.order_id=" . intval($order_id) . 
	       " GROUP BY og.goods_id ORDER BY rec_id DESC";
	$res = $GLOBALS['db']->query($sql);
	while ($row = $GLOBALS['db']->fetchRow($res)) {
		$goods_list[$row['goods_id']]                             =  $row;
		$goods_list[$row['goods_id']]['short_goods_name']         =  sub_str($row['goods_name'], 16);
		$goods_list[$row['goods_id']]['goods_sn']                 =  sub_str($row['goods_sn'], 0);
		$goods_list[$row['goods_id']]['formated_norm_price']      =  price_format(abs($row['norm_price']), false);		
		$goods_list[$row['goods_id']]['formated_discount']        =  sprintf('%s', $row['discount']);
		$goods_list[$row['goods_id']]['formated_actual_price']    =  price_format(abs($row['actual_price']), false);		  
		$goods_list[$row['goods_id']]['subtotal_number']          =  intval($row['subtotal_number']);
		$goods_list[$row['goods_id']]['formated_subtotal_amount'] =  price_format(abs($row['subtotal_amount']), false);	
	}
	$sql = "SELECT og.*,g.goods_name,g.goods_sn,IFNULL(c.color_name,'默认') color_name,IFNULL(s.size_name,'默认') size_name,
	       IFNULL(b.brand_name, '') AS brand_name FROM " . $GLOBALS['os']->table('scm_'.$str_type.'_goods') . 
	       ' og LEFT JOIN ' . $GLOBALS['os']->table('goods') . ' g ON og.goods_id=g.goods_id LEFT JOIN ' . 
	       $GLOBALS['os']->table('color') . " c ON og.color_id=c.color_id LEFT JOIN " . $GLOBALS['os']->table('size') . 
	       ' s ON og.size_id=s.size_id LEFT JOIN ' . $GLOBALS['os']->table('brand') . ' b ON  g.brand_id=b.brand_id ' . 
	       ' WHERE og.order_id=' . intval($order_id) . ' ORDER BY og.rec_id DESC';
	$result = $GLOBALS['db']->query($sql);
	while ($row = $GLOBALS['db']->fetchRow($result)) {
		if(isset($goods_list[$row['goods_id']]) && is_array($goods_list[$row['goods_id']])){		
			$goods_list[$row['goods_id']]['sub_list'][$row['rec_id']]                             =  $row;
			$goods_list[$row['goods_id']]['sub_list'][$row['rec_id']]['short_goods_name']         =  sub_str($row['goods_name'], 16);
			$goods_list[$row['goods_id']]['sub_list'][$row['rec_id']]['goods_sn']                 =  sub_str($row['goods_sn'], 0);
			$goods_list[$row['goods_id']]['sub_list'][$row['rec_id']]['formated_norm_price']      =  price_format(abs($row['norm_price']), false);		
			$goods_list[$row['goods_id']]['sub_list'][$row['rec_id']]['formated_discount']        =  sprintf('%s', $row['discount']);
			$goods_list[$row['goods_id']]['sub_list'][$row['rec_id']]['formated_actual_price']    =  price_format(abs($row['actual_price']), false);		  
			$goods_list[$row['goods_id']]['sub_list'][$row['rec_id']]['subtotal_number']          =  intval($row['goods_number']);
			$goods_list[$row['goods_id']]['sub_list'][$row['rec_id']]['formated_subtotal_amount'] =  price_format(abs($row['actual_amount']), false);	
		    $goods_list[$row['goods_id']]['sub_list'][$row['rec_id']]['goods_attr']               =  '颜色:' . $row['color_name'] . '&nbsp;&nbsp;尺码:' . $row['size_name'];
		}
	}
	return $goods_list;
}

function create_scm_enter_order($purchase_order_id, $order_sn){
    $sql = "INSERT INTO " . $GLOBALS['os']->table('scm_enter_order') . "(order_sn, supplier_id, depot_id, " . 
    	   "seat_id, discount, deliver_time, goods_number, order_amount, order_status, order_brief, add_time) " . 
    	   "SELECT '$order_sn', supplier_id, depot_id, seat_id, discount, deliver_time, goods_number, order_amount, " . 
    	   "0, order_brief, " . gmtime() . " FROM " . $GLOBALS['os']->table('scm_purchase_order') . " WHERE order_id=" . 
    	   intval($purchase_order_id);
    $res = $GLOBALS['db']->query($sql);	
    
    if ($res !== false)
    {    
    	return $GLOBALS['db']->insert_id();
    }
    else
    {
        return false;
    } 
}

function create_scm_enter_goods($order_id, $purchase_order_id)
{
    $sql = "INSERT INTO " . $GLOBALS['os']->table('scm_enter_goods') . "(order_id, goods_id, color_id, " . 
    	   "size_id, goods_number, norm_price, discount, actual_price, norm_amount, actual_amount) " . 
    	   "SELECT " . intval($order_id) . ", goods_id, color_id, size_id, goods_number, norm_price, discount, " .
    	   "actual_price, norm_amount, actual_amount FROM " . $GLOBALS['os']->table('scm_purchase_goods') . 
    	   " WHERE order_id=" . intval($purchase_order_id);
    $res = $GLOBALS['db']->query($sql);
    
    if ($res !== false)
    {    
    	return true;
    }
    else
    {
        return false;
    } 
}


function create_scm_loss_order($check_order_id, $order_sn)
{	
    $sql = "INSERT INTO " . $GLOBALS['os']->table('scm_loss_order') . "(order_sn, depot_id, seat_id, " . 
    	   "goods_number, order_amount, order_status, order_brief, add_time) SELECT '$order_sn', " . 
    	   "depot_id, seat_id, goods_number, order_amount, 0, '', " . gmtime() . " FROM " . 
    	   $GLOBALS['os']->table('scm_check_order') . " WHERE order_id=" . intval($check_order_id);
    $res = $GLOBALS['db']->query($sql);	
    
    if ($res !== false)
    {    
    	return $GLOBALS['db']->insert_id();
    }
    else
    {
        return false;
    } 
}

function create_scm_loss_goods($order_id, $check_order_id)
{	
	$sql = "SELECT goods_id,color_id,size_id,goods_number,actual_price,actual_amount FROM " . 
		   $GLOBALS['os']->table('scm_check_goods') . " WHERE order_id=" . intval($check_order_id);
	$res = $GLOBALS['db']->query($sql);
    
	while ($row=$GLOBALS['db']->fetchRow($res)) {
		$sql_in = "SELECT goods_number_actual FROM " . $GLOBALS['os']->table('goods_inventory') . 
		          " WHERE goods_id=$row[goods_id] AND color_id=$row[color_id] AND size_id=$row[size_id]";
		$inventory_num = $GLOBALS['db']->getOne($sql_in);	
		$inventory_num = is_numeric($inventory_num) ? intval($inventory_num) : 0;
		$loss_num      = intval($row['goods_number']-$inventory_num);
    	$sql_ls = "INSERT INTO " . $GLOBALS['os']->table('scm_loss_goods') . "(order_id, goods_id, color_id, " . 
    	          "size_id, goods_number, goods_number_inventory, goods_number_loss, actual_price, actual_amount," . 
    	          " loss_amount) VALUES (" . intval($order_id) . ", $row[goods_id], $row[color_id], " . 
    	          "$row[size_id], $row[goods_number], $inventory_num, $loss_num, $row[actual_price], " . 
    	          "$row[actual_amount], $loss_num*$row[actual_price])";
    	$GLOBALS['db']->query($sql_ls);			
	}
    if ($res !== false)
    {    
    	return true;
    }
    else
    {
        return false;
    } 
}

function create_scm_rectify_order($loss_order_id, $order_sn)
{	    
    $sql = "INSERT INTO " . $GLOBALS['os']->table('scm_rectify_order') . "(order_sn, depot_id, " . 
    	   "seat_id,goods_number,goods_number_loss,order_amount,order_amount_loss,order_status, " . 
    	   "order_brief, is_freedom, add_time, is_temp) SELECT '$order_sn', depot_id, seat_id, " . 
    	   "goods_number, goods_number_loss, order_amount, order_amount_loss, 0, '', 0, " . gmtime() . 
    	   ", 0 FROM " . $GLOBALS['os']->table('scm_loss_order') . " WHERE order_id=" . intval($loss_order_id);
    $res = $GLOBALS['db']->query($sql);	
    if ($res !== false)
    {    
    	return $GLOBALS['db']->insert_id();
    }
    else
    {
        return false;
    } 
}

function create_scm_rectify_goods($order_id, $loss_order_id)
{
    $sql = "INSERT INTO " . $GLOBALS['os']->table('scm_rectify_goods') . "(order_id, goods_id, color_id, size_id, " . 
    	   "goods_number, goods_number_inventory, goods_number_loss, actual_price, actual_amount, loss_amount) " . 
    	   "SELECT " . intval($order_id) . ", goods_id, color_id, size_id, goods_number, goods_number_inventory, " . 
    	   "goods_number_loss, actual_price, actual_amount, loss_amount FROM " . $GLOBALS['os']->table('scm_loss_goods') .
    	   " WHERE order_id=" . intval($loss_order_id);
    $res = $GLOBALS['db']->query($sql);
    
    if ($res !== false)
    {    
    	return true;
    }
    else
    {
        return false;
    } 
}

function scm_enter_order_list(){
    $result = get_filter();
    if ($result === false)
    {
        /* 初始化分页参数 */
        $filter = array();
        $filter['sort_by']    = empty($_REQUEST['sort_by']) ? 'order_id' : trim($_REQUEST['sort_by']);
        $filter['sort_order'] = empty($_REQUEST['sort_order']) ? 'DESC' : trim($_REQUEST['sort_order']);
        $filter['order_sn'] = empty($_REQUEST['order_sn']) ? '' : trim($_REQUEST['order_sn']);
        $filter['status']     = (!is_numeric($_REQUEST['status']) || $_REQUEST['status']<0) ? -1 : intval($_REQUEST['status']);
        if (!empty($_GET['is_ajax']) && $_GET['is_ajax'] == 1)
        {
            $_REQUEST['supplier_name'] = json_str_iconv($_REQUEST['supplier_name']);
        }
        $filter['supplier_name'] = empty($_REQUEST['supplier_name']) ? '' : trim($_REQUEST['supplier_name']); 
        $filter['start_add_time'] = empty($_REQUEST['start_add_time']) ? '' : (strpos($_REQUEST['start_add_time'], '-') > 0 ?  local_strtotime($_REQUEST['start_add_time']) : $_REQUEST['start_add_time']);
        $filter['end_add_time'] = empty($_REQUEST['end_add_time']) ? '' : (strpos($_REQUEST['end_add_time'], '-') > 0 ?  local_strtotime($_REQUEST['end_add_time']) : $_REQUEST['end_add_time']);	
        $filter['start_deliver_time'] = empty($_REQUEST['start_deliver_time']) ? '' : (strpos($_REQUEST['start_deliver_time'], '-') > 0 ?  local_strtotime($_REQUEST['start_deliver_time']) : $_REQUEST['start_deliver_time']);
        $filter['end_deliver_time'] = empty($_REQUEST['end_deliver_time']) ? '' : (strpos($_REQUEST['end_deliver_time'], '-') > 0 ?  local_strtotime($_REQUEST['end_deliver_time']) : $_REQUEST['end_deliver_time']);

        $where = 'WHERE 1 ';
        if ($filter['order_sn'])
        {
            $where .= " AND o.order_sn LIKE '%" . mysql_like_quote($filter['order_sn']) . "%'";
        }
        if ($filter['supplier_name'])
        {
            $where .= " AND s.supplier_name LIKE '%" . mysql_like_quote($filter['supplier_name']) . "%'";
        } 
        if($filter['status']>=0){
        	$where .= " AND o.order_status=$filter[status]";
        } 
        if ($filter['start_add_time'])
        {
            $where .= " AND o.add_time >= '$filter[start_add_time]'";
        }
        if ($filter['end_add_time'])
        {
            $where .= " AND o.add_time <= '$filter[end_add_time]'";
        }
        if ($filter['start_deliver_time'])
        {
            $where .= " AND o.deliver_time >= '$filter[start_deliver_time]'";
        }
        if ($filter['end_deliver_time'])
        {
            $where .= " AND o.deliver_time <= '$filter[end_deliver_time]'";
        }                     
        /* 查询记录总数，计算分页数 */
   		$sql = "SELECT COUNT(*) FROM " . $GLOBALS['os']->table('scm_enter_order') . " o LEFT JOIN " . 
   		       $GLOBALS['os']->table('supplier') . " s ON o.supplier_id=s.supplier_id " . $where;
        $filter['record_count'] = $GLOBALS['db']->getOne($sql);
        $filter = page_and_size($filter);

        /* 查询记录 */
        $sql = "SELECT o.*,s.supplier_name FROM " . $GLOBALS['os']->table('scm_enter_order') . " o LEFT JOIN " . 
   		       $GLOBALS['os']->table('supplier') . " s ON o.supplier_id=s.supplier_id " . $where .
   		       " ORDER BY $filter[sort_by] $filter[sort_order]";
        set_filter($filter, $sql);
    }
    else
    {
        $sql    = $result['sql'];
        $filter = $result['filter'];
    }
    $res = $GLOBALS['db']->selectLimit($sql, $filter['page_size'], $filter['start']);

    $arr = array();
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
		$row['status']  				    = scm_order_status('enter', $row['order_status']);
		$row['formated_discount']  		    = sprintf('%s', $row['discount']);
      	$row['formated_order_amount']	    = price_format(abs($row['order_amount']), false);
      	$row['formated_add_time']           = local_date('Y-m-d', $row['add_time']);
      	$row['formated_deliver_time']       = local_date('Y-m-d', $row['deliver_time']);
      	$row['short_supplier_name']         = sub_str($row['supplier_name'], 10);
        $arr[] = $row;
    }
    return array('item' => $arr, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);	
}

function scm_enter_order_info($order_id, $order_sn = ''){
  /* 计算订单各种费用之和的语句 */
    $order_id = intval($order_id);
    if ($order_id > 0)
    {
        $sql = 'SELECT o.*,s.supplier_name,po.order_sn purchase_order_sn FROM ' . $GLOBALS['os']->table('scm_enter_order') . 
        	   ' o LEFT JOIN ' . $GLOBALS['os']->table('supplier') . ' s ON o.supplier_id=s.supplier_id LEFT JOIN ' . 
        	   $GLOBALS['os']->table('scm_purchase_order') . " po ON o.purchase_order_id=po.order_id WHERE o.order_id = '$order_id'";
    }
    else
    {
        $sql = 'SELECT o.*,s.supplier_name,po.order_sn purchase_order_sn FROM ' . $GLOBALS['os']->table('scm_enter_order') . 
        	   ' o LEFT JOIN ' . $GLOBALS['os']->table('supplier') . ' s ON o.supplier_id=s.supplier_id LEFT JOIN ' . 		
               $GLOBALS['os']->table('scm_purchase_order') . " po ON o.purchase_order_id=po.order_id WHERE o.order_sn = '$order_sn'";	
    }
    $order = $GLOBALS['db']->getRow($sql);

    /* 格式化金额字段 */
    if ($order)
    {
    	$order['short_supplier_name']         = sub_str($order['supplier_name'], 10);
        $order['depot_name']                  = ' 默认 ';
        $order['seat_name']                   = ' 默认 ';
        $order['formated_discount']           = sprintf('%s', $order['discount']);
     	$order['formated_add_time']           = local_date('Y-m-d', $order['add_time']); 
     	$order['formated_deliver_time']       = local_date('Y-m-d', $order['deliver_time']);       
        $order['formated_order_amount']       = price_format(abs($order['order_amount']), false);
		$order['status']                      = scm_order_status('enter', $order['order_status']);
    }

    return $order;	
}

function check_enter_goods_list($order_id){
	$goods_list = array();
	$sql = "SELECT g.goods_name,g.goods_sn,c.color_code,IFNULL(c.color_name,'默认') color_name,s.size_code,IFNULL(s.size_name,'默认') size_name," . 
	       "og.goods_number,og.send_number,gb.barcode FROM " . $GLOBALS['os']->table('scm_enter_goods') . " og LEFT JOIN " . 
	       $GLOBALS['os']->table('goods') . " g ON og.goods_id=g.goods_id LEFT JOIN " . $GLOBALS['os']->table('color') . 
	       " c ON og.color_id=c.color_id LEFT JOIN " . $GLOBALS['os']->table('size') . " s ON og.size_id=s.size_id LEFT JOIN " . 
	       $GLOBALS['os']->table('goods_barcode') . " gb ON og.goods_id=gb.goods_id AND og.color_id=gb.color_id AND og.size_id=gb.size_id " . 
	       "  WHERE og.order_id=" . intval($order_id) . " ORDER BY og.rec_id DESC";
	$result = $GLOBALS['db']->query($sql);
	while ($row = $GLOBALS['db']->fetchRow($result)) {	
			$goods_list[]           =    $row;
	}
	return $goods_list;	
}

function scm_return_order_list(){
    $result = get_filter();
    if ($result === false)
    {
        /* 初始化分页参数 */
        $filter = array();
        $filter['sort_by']    = empty($_REQUEST['sort_by']) ? 'order_id' : trim($_REQUEST['sort_by']);
        $filter['sort_order'] = empty($_REQUEST['sort_order']) ? 'DESC' : trim($_REQUEST['sort_order']);
        $filter['order_sn']   = empty($_REQUEST['order_sn']) ? '' : trim($_REQUEST['order_sn']);
        $filter['status']     = (!is_numeric($_REQUEST['status']) || $_REQUEST['status']<0) ? -1 : intval($_REQUEST['status']);
        if (!empty($_GET['is_ajax']) && $_GET['is_ajax'] == 1)
        {
            $_REQUEST['supplier_name'] = json_str_iconv($_REQUEST['supplier_name']);
        }
        $filter['supplier_name']       = empty($_REQUEST['supplier_name']) ? '' : trim($_REQUEST['supplier_name']); 
        $filter['start_add_time']      = empty($_REQUEST['start_add_time']) ? '' : (strpos($_REQUEST['start_add_time'], '-') > 0 ?  local_strtotime($_REQUEST['start_add_time']) : $_REQUEST['start_add_time']);
        $filter['end_add_time']        = empty($_REQUEST['end_add_time']) ? '' : (strpos($_REQUEST['end_add_time'], '-') > 0 ?  local_strtotime($_REQUEST['end_add_time']) : $_REQUEST['end_add_time']);	
        $filter['start_deliver_time']  = empty($_REQUEST['start_deliver_time']) ? '' : (strpos($_REQUEST['start_deliver_time'], '-') > 0 ?  local_strtotime($_REQUEST['start_deliver_time']) : $_REQUEST['start_deliver_time']);
        $filter['end_deliver_time']    = empty($_REQUEST['end_deliver_time']) ? '' : (strpos($_REQUEST['end_deliver_time'], '-') > 0 ?  local_strtotime($_REQUEST['end_deliver_time']) : $_REQUEST['end_deliver_time']);

        $where = 'WHERE 1 ';
        if ($filter['order_sn'])
        {
            $where .= " AND o.order_sn LIKE '%" . mysql_like_quote($filter['order_sn']) . "%'";
        }
        if($filter['status']>=0){
        	$where .= " AND o.order_status=$filter[status]";
        }
        if ($filter['supplier_name'])
        {
            $where .= " AND o.supplier_name LIKE '%" . mysql_like_quote($filter['supplier_name']) . "%'";
        }  
        if ($filter['start_add_time'])
        {
            $where .= " AND o.add_time >= '$filter[start_add_time]'";
        }
        if ($filter['end_add_time'])
        {
            $where .= " AND o.add_time <= '$filter[end_add_time]'";
        }
        if ($filter['start_deliver_time'])
        {
            $where .= " AND o.deliver_time >= '$filter[start_deliver_time]'";
        }
        if ($filter['end_deliver_time'])
        {
            $where .= " AND o.deliver_time <= '$filter[end_deliver_time]'";
        }                     
        /* 查询记录总数，计算分页数 */
   		$sql = "SELECT COUNT(*) FROM " . $GLOBALS['os']->table('scm_return_order') . " o LEFT JOIN " . 
   		       $GLOBALS['os']->table('supplier') . " s ON o.supplier_id=s.supplier_id " . $where;
        $filter['record_count'] = $GLOBALS['db']->getOne($sql);
        $filter = page_and_size($filter);

        /* 查询记录 */
        $sql = "SELECT o.*,s.supplier_name FROM " . $GLOBALS['os']->table('scm_return_order') . " o LEFT JOIN " . 
   		       $GLOBALS['os']->table('supplier') . " s ON o.supplier_id=s.supplier_id " . $where .
   		       " ORDER BY $filter[sort_by] $filter[sort_order]";
        set_filter($filter, $sql);
    }
    else
    {
        $sql    = $result['sql'];
        $filter = $result['filter'];
    }
    $res = $GLOBALS['db']->selectLimit($sql, $filter['page_size'], $filter['start']);

    $arr = array();
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
		$row['status']  				    = scm_order_status('return', $row['order_status']);
		$row['formated_discount']  		    = sprintf('%s', $row['discount']);
      	$row['formated_order_amount']	    = price_format(abs($row['order_amount']), false);
      	$row['formated_add_time']           = local_date('Y-m-d', $row['add_time']);
      	$row['formated_deliver_time']       = local_date('Y-m-d', $row['deliver_time']);
      	$row['short_supplier_name']         = sub_str($row['supplier_name'], 10);
        $arr[] = $row;
    }
    return array('item' => $arr, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);	
}

function scm_return_order_info($order_id){
    /* 计算订单各种费用之和的语句 */
    $order_id = intval($order_id);
    if ($order_id > 0)
    {
        $sql = 'SELECT o.*,s.supplier_name FROM ' . $GLOBALS['os']->table('scm_return_order') . 
               ' o LEFT JOIN ' . $GLOBALS['os']->table('supplier') . ' s ON o.supplier_id=s.supplier_id ' . 
               " WHERE o.order_id = '$order_id'";	
    }
    else
    {
        $sql = 'SELECT o.*,s.supplier_name FROM ' . $GLOBALS['os']->table('scm_return_order') . 
        	   ' o LEFT JOIN ' . $GLOBALS['os']->table('supplier') . ' s ON o.supplier_id=s.supplier_id ' . 		
               " WHERE o.order_sn = '$order_sn'";	
    }
    $order = $GLOBALS['db']->getRow($sql);

    /* 格式化字段 */
    if ($order)
    {
		$order['short_supplier_name']         = sub_str($order['supplier_name'], 10);
        $order['depot_name']                  = ' 默认 ';
        $order['seat_name']                   = ' 默认 ';
        $order['formated_discount']           = sprintf('%s', $order['discount']);
     	$order['formated_add_time']           = local_date('Y-m-d', $order['add_time']); 
     	$order['formated_deliver_time']       = local_date('Y-m-d', $order['deliver_time']);       
        $order['formated_order_amount']       = price_format(abs($order['order_amount']), false);
		$order['status']                      = scm_order_status('return', $order['order_status']);
    }

    return $order;	
}

function check_return_goods_list($order_id){
	$goods_list = array();
	$sql = "SELECT g.goods_name,g.goods_sn,c.color_code,IFNULL(c.color_name,'默认') color_name,s.size_code,IFNULL(s.size_name,'默认') size_name," . 
	       "og.goods_number,og.send_number,gb.barcode FROM " . $GLOBALS['os']->table('scm_return_goods') . " og LEFT JOIN " . 
	       $GLOBALS['os']->table('goods') . " g ON og.goods_id=g.goods_id LEFT JOIN " . $GLOBALS['os']->table('color') . 
	       " c ON og.color_id=c.color_id LEFT JOIN " . $GLOBALS['os']->table('size') . " s ON og.size_id=s.size_id LEFT JOIN " . 
	       $GLOBALS['os']->table('goods_barcode') . " gb ON og.goods_id=gb.goods_id AND og.color_id=gb.color_id AND og.size_id=gb.size_id " . 
	       "  WHERE og.order_id=" . intval($order_id) . " ORDER BY og.rec_id DESC";
	$result = $GLOBALS['db']->query($sql);
	while ($row = $GLOBALS['db']->fetchRow($result)) {	
			$goods_list[]           =    $row;
	}
	return $goods_list;	
}

function scm_return_goods($order_id){
	static $goods_list = array();
	$sql = "SELECT og.*,SUM(og.goods_number) subtotal_number,SUM(og.actual_amount) subtotal_amount,g.goods_name," . 
		   "g.goods_sn FROM " . $GLOBALS['os']->table('scm_return_goods') . " og LEFT JOIN " . 
		   $GLOBALS['os']->table('goods') . " g ON og.goods_id=g.goods_id WHERE og.order_id=" . intval($order_id) . 
	       " GROUP BY og.goods_id ORDER BY rec_id DESC";
	$res = $GLOBALS['db']->query($sql);
	while ($row = $GLOBALS['db']->fetchRow($res)) {
		$goods_list[$row['goods_id']]['order_id']                 =  $row['order_id'];
		$goods_list[$row['goods_id']]['goods_id']                 =  $row['goods_id'];
		$goods_list[$row['goods_id']]['goods_name']               =  sub_str($row['goods_name'], 0);
		$goods_list[$row['goods_id']]['goods_sn']                 =  sub_str($row['goods_sn'], 0);
		$goods_list[$row['goods_id']]['formated_norm_price']      =  price_format(abs($row['norm_price']), false);		
		$goods_list[$row['goods_id']]['formated_discount']        =  sprintf('%s', $row['discount']);
		$goods_list[$row['goods_id']]['formated_actual_price']    =  price_format(abs($row['actual_price']), false);		  
		$goods_list[$row['goods_id']]['subtotal_number']          =  intval($row['subtotal_number']);
		$goods_list[$row['goods_id']]['formated_subtotal_amount'] =  price_format(abs($row['subtotal_amount']), false);		      		
	}
	$sql = "SELECT og.*,g.goods_name,g.goods_sn,IFNULL(c.color_name,'默认') color_name,IFNULL(s.size_name,'默认') size_name,
	       IFNULL(b.brand_name, '') AS brand_name FROM " . $GLOBALS['os']->table('scm_return_goods') . 
	       ' og LEFT JOIN ' . $GLOBALS['os']->table('goods') . ' g ON og.goods_id=g.goods_id LEFT JOIN ' . 
	       $GLOBALS['os']->table('color') . " c ON og.color_id=c.color_id LEFT JOIN " . $GLOBALS['os']->table('size') . 
	       ' s ON og.size_id=s.size_id LEFT JOIN ' . $GLOBALS['os']->table('brand') . ' b ON  g.brand_id=b.brand_id ' . 
	       ' WHERE og.order_id=' . intval($order_id) . ' ORDER BY og.rec_id DESC';
	$result = $GLOBALS['db']->query($sql);
	$arr_color = array();
	$arr_size = array();
	while ($row = $GLOBALS['db']->fetchRow($result)) {
		if(isset($goods_list[$row['goods_id']]) && is_array($goods_list[$row['goods_id']])){
			if(!is_array($arr_color[$row['goods_id']]) || !in_array($row['color_name'], $arr_color[$row['goods_id']])) 
					$arr_color[$row['goods_id']][]=$row['color_name'];
			if(!is_array($arr_size[$row['goods_id']]) || !in_array($row['size_name'], $arr_size[$row['goods_id']])) 
					$arr_size[$row['goods_id']][]=$row['size_name'];			
			$goods_list[$row['goods_id']]['sub_list'][$row['rec_id']]['order_id']                 =  $row['order_id'];
			$goods_list[$row['goods_id']]['sub_list'][$row['rec_id']]['goods_id']                 =  $row['goods_id'];
			$goods_list[$row['goods_id']]['sub_list'][$row['rec_id']]['color_id']                 =  $row['color_id'];
			$goods_list[$row['goods_id']]['sub_list'][$row['rec_id']]['size_id']                  =  $row['size_id'];
			$goods_list[$row['goods_id']]['sub_list'][$row['rec_id']]['goods_name']               =  sub_str($row['goods_name'], 0);
			$goods_list[$row['goods_id']]['sub_list'][$row['rec_id']]['goods_sn']                 =  sub_str($row['goods_sn'], 0);
			$goods_list[$row['goods_id']]['sub_list'][$row['rec_id']]['formated_norm_price']      =  price_format(abs($row['norm_price']), false);		
			$goods_list[$row['goods_id']]['sub_list'][$row['rec_id']]['formated_discount']        =  sprintf('%s', $row['discount']); 
			$goods_list[$row['goods_id']]['sub_list'][$row['rec_id']]['formated_actual_price']    =  price_format(abs($row['actual_price']), false);		  
			$goods_list[$row['goods_id']]['sub_list'][$row['rec_id']]['subtotal_number']          =  intval($row['goods_number']);
			$goods_list[$row['goods_id']]['sub_list'][$row['rec_id']]['formated_subtotal_amount'] =  price_format(abs($row['actual_amount']), false);	
		    $goods_list[$row['goods_id']]['sub_list'][$row['rec_id']]['goods_attr']               =  '颜色:' . $row['color_name'] . '&nbsp;&nbsp;尺码:' . $row['size_name'];
		}	
	    $goods_list[$row['goods_id']]['goods_attr']                                               =  '颜色:' . implode(',', $arr_color[$row['goods_id']]) . '&nbsp;&nbsp;尺码:' . implode(',', $arr_size[$row['goods_id']]);	
	}
	return $goods_list;	
}

function scm_check_goods($order_id){
	static $goods_list = array();
	$sql = "SELECT og.*,SUM(og.goods_number) subtotal_number,SUM(og.actual_amount) subtotal_amount,g.goods_name," . 
		   "g.goods_sn FROM " . $GLOBALS['os']->table('scm_check_goods') . " og LEFT JOIN " . 
		   $GLOBALS['os']->table('goods') . " g ON og.goods_id=g.goods_id WHERE og.order_id=" . intval($order_id) . 
	       " GROUP BY og.goods_id ORDER BY rec_id DESC";
	$res = $GLOBALS['db']->query($sql);
	while ($row = $GLOBALS['db']->fetchRow($res)) {
		$goods_list[$row['goods_id']]['order_id']                 =  $row['order_id'];
		$goods_list[$row['goods_id']]['goods_id']                 =  $row['goods_id'];
		$goods_list[$row['goods_id']]['goods_name']               =  sub_str($row['goods_name'], 0);
		$goods_list[$row['goods_id']]['goods_sn']                 =  sub_str($row['goods_sn'], 0);
		$goods_list[$row['goods_id']]['formated_norm_price']      =  price_format(abs($row['norm_price']), false);		
		$goods_list[$row['goods_id']]['formated_discount']        =  sprintf('%s', $row['discount']);
		$goods_list[$row['goods_id']]['formated_actual_price']    =  price_format(abs($row['actual_price']), false);		  
		$goods_list[$row['goods_id']]['subtotal_number']          =  intval($row['subtotal_number']);
		$goods_list[$row['goods_id']]['formated_subtotal_amount'] =  price_format(abs($row['subtotal_amount']), false);		      		
	}
	$sql = "SELECT og.*,g.goods_name,g.goods_sn,IFNULL(c.color_name,'默认') color_name,IFNULL(s.size_name,'默认') size_name,
	       IFNULL(b.brand_name, '') AS brand_name FROM " . $GLOBALS['os']->table('scm_check_goods') . 
	       ' og LEFT JOIN ' . $GLOBALS['os']->table('goods') . ' g ON og.goods_id=g.goods_id LEFT JOIN ' . 
	       $GLOBALS['os']->table('color') . " c ON og.color_id=c.color_id LEFT JOIN " . $GLOBALS['os']->table('size') . 
	       ' s ON og.size_id=s.size_id LEFT JOIN ' . $GLOBALS['os']->table('brand') . ' b ON  g.brand_id=b.brand_id ' . 
	       ' WHERE og.order_id=' . intval($order_id) . ' ORDER BY og.rec_id DESC';
	$result = $GLOBALS['db']->query($sql);
	$arr_color = array();
	$arr_size = array();
	while ($row = $GLOBALS['db']->fetchRow($result)) {
		if(isset($goods_list[$row['goods_id']]) && is_array($goods_list[$row['goods_id']])){
			if(!is_array($arr_color[$row['goods_id']]) || !in_array($row['color_name'], $arr_color[$row['goods_id']])) 
					$arr_color[$row['goods_id']][]=$row['color_name'];
			if(!is_array($arr_size[$row['goods_id']]) || !in_array($row['size_name'], $arr_size[$row['goods_id']])) 
					$arr_size[$row['goods_id']][]=$row['size_name'];			
			$goods_list[$row['goods_id']]['sub_list'][$row['rec_id']]['order_id']                 =  $row['order_id'];
			$goods_list[$row['goods_id']]['sub_list'][$row['rec_id']]['goods_id']                 =  $row['goods_id'];
			$goods_list[$row['goods_id']]['sub_list'][$row['rec_id']]['color_id']                 =  $row['color_id'];
			$goods_list[$row['goods_id']]['sub_list'][$row['rec_id']]['size_id']                  =  $row['size_id'];
			$goods_list[$row['goods_id']]['sub_list'][$row['rec_id']]['goods_name']               =  sub_str($row['goods_name'], 0);
			$goods_list[$row['goods_id']]['sub_list'][$row['rec_id']]['goods_sn']                 =  sub_str($row['goods_sn'], 0);
			$goods_list[$row['goods_id']]['sub_list'][$row['rec_id']]['formated_norm_price']      =  price_format(abs($row['norm_price']), false);		
			$goods_list[$row['goods_id']]['sub_list'][$row['rec_id']]['formated_discount']        =  sprintf('%s', $row['discount']);
			$goods_list[$row['goods_id']]['sub_list'][$row['rec_id']]['formated_actual_price']    =  price_format(abs($row['actual_price']), false);		  
			$goods_list[$row['goods_id']]['sub_list'][$row['rec_id']]['subtotal_number']          =  intval($row['goods_number']);
			$goods_list[$row['goods_id']]['sub_list'][$row['rec_id']]['formated_subtotal_amount'] =  price_format(abs($row['actual_amount']), false);	
		    $goods_list[$row['goods_id']]['sub_list'][$row['rec_id']]['goods_attr']               =  '颜色:' . $row['color_name'] . '&nbsp;&nbsp;尺码:' . $row['size_name'];
		}	
	    $goods_list[$row['goods_id']]['goods_attr']                                               =  '颜色:' . implode(',', $arr_color[$row['goods_id']]) . '&nbsp;&nbsp;尺码:' . implode(',', $arr_size[$row['goods_id']]);	
	}
	return $goods_list;
}


function show_order_goods_list($tb, $order_id, $goods_id){
	$sql =  "SELECT og.*,g.goods_name,g.goods_sn,IFNULL(c.color_name,'默认') color_name,
	        IFNULL(s.size_name,'默认') size_name,IFNULL(b.brand_name, '') AS brand_name FROM " . 
	        $GLOBALS['os']->table($tb) . ' og LEFT JOIN ' . $GLOBALS['os']->table('goods') . 
	        ' g ON og.goods_id=g.goods_id LEFT JOIN ' . $GLOBALS['os']->table('color') . 
	        ' c ON og.color_id=c.color_id LEFT JOIN ' . $GLOBALS['os']->table('size') . 
	        ' s ON og.size_id=s.size_id LEFT JOIN ' . $GLOBALS['os']->table('brand') . 
	        ' b ON g.brand_id=b.brand_id WHERE og.order_id=' . intval($order_id) . 
	        ' AND og.goods_id=' . intval($goods_id) . ' ORDER BY og.rec_id DESC';
	$result = $GLOBALS['db']->query($sql);
	$goods_list = array();
	while ($row = $GLOBALS['db']->fetchRow($result)) {
		$goods_list[$row['rec_id']]['goods_name']              =  substr($row['goods_name'], 0);
		$goods_list[$row['rec_id']]['brand_name']              =  substr($row['brand_name'], 0);
		$goods_list[$row['rec_id']]['goods_sn']                =  substr($row['goods_sn'], 0);
		$goods_list[$row['rec_id']]['formated_norm_price']     =  price_format($row['norm_price']);		
		$goods_list[$row['rec_id']]['formated_discount']       =  sprintf('%s', floatval($row['discount']));
		$goods_list[$row['rec_id']]['formated_actual_price']   =  price_format($row['actual_price']);
		$goods_list[$row['rec_id']]['goods_number']            =  $row['goods_number'];
		$goods_list[$row['rec_id']]['goods_number_inventory']  =  $row['goods_number_inventory'];
		$goods_list[$row['rec_id']]['formated_num_loss']  	   =  ($row['goods_number_loss'] > 0 ? '-' : '+') . abs($row['goods_number_loss']);
		$goods_list[$row['rec_id']]['formated_num_rectify']    =  ($row['goods_number_rectify'] > 0 ? '-' : '+') . abs($row['goods_number_rectify']);
		$goods_list[$row['rec_id']]['goods_attr']              =  '颜色:' . $row['color_name'] . '&nbsp;尺码:' . $row['size_name'];
		$goods_list[$row['rec_id']]['formated_subtotal']       =  price_format($row['actual_price'] * $row['goods_number']);
	    $goods_list[$row['rec_id']]['formated_loss_subtotal']  =  price_format($row['actual_price'] * (($row['goods_number_loss'] > 0 ? '-' : '+') . abs($row['goods_number_loss'])));
	}  
	return $goods_list;	
}





function scm_loss_order_info($order_id, $order_sn = ''){
    /* 计算订单各种费用之和的语句 */
    $order_id = intval($order_id);
    if ($order_id > 0)
    {
        $sql = "SELECT o.* FROM " . $GLOBALS['os']->table('scm_loss_order') . " o WHERE o.order_id = '$order_id'";	
    }
    else
    {
        $sql = "SELECT o.* FROM " . $GLOBALS['os']->table('scm_loss_order') . " o WHERE o.order_sn = '$order_sn'";	
    }
    $order = $GLOBALS['db']->getRow($sql);

    /* 格式化金额字段 */
    if ($order)
    {
        $order['depot_name']                  = ' 默认 ';
        $order['seat_name']                   = ' 默认 ';
        $order['formated_discount']           = sprintf('%s', $order['discount']);
     	$order['formated_add_time']           = local_date('Y-m-d', $order['add_time']);     
        $order['formated_order_amount']       = price_format(abs($order['order_amount']), false);
        $order['formated_order_amount_loss']  = price_format($order['order_amount_loss'], false);
		$order['status']                      = scm_order_status('loss', $order['order_status']);
    }

    return $order;	
}

function scm_loss_goods($str_type, $order_id){
	static $arr_type  =  array('loss', 'rectify');
	$goods_list = array();
	$sql = "SELECT og.*,SUM(og.goods_number) subtotal_number,SUM(og.actual_amount) subtotal_amount," . 
	       "SUM(og.goods_number_inventory) subtotal_number_in,SUM(og.goods_number_loss) subtotal_number_loss," . 
	       "SUM(og.loss_amount) subtotal_loss_amount,g.goods_name,g.goods_sn FROM " . 
	       $GLOBALS['os']->table('scm_'.$str_type.'_goods') . " og LEFT JOIN " . $GLOBALS['os']->table('goods') . 
	       " g ON og.goods_id=g.goods_id WHERE og.order_id=$order_id GROUP BY og.goods_id ORDER BY rec_id DESC";
	$res = $GLOBALS['db']->query($sql);
	while ($row = $GLOBALS['db']->fetchRow($res)) {
		$goods_list[$row['goods_id']]                                   =  $row;
		$goods_list[$row['goods_id']]['short_goods_name']               =  sub_str($row['goods_name'], 16);
		$goods_list[$row['goods_id']]['goods_sn']                       =  sub_str($row['goods_sn'], 0);
		$goods_list[$row['goods_id']]['formated_actual_price']          =  price_format(abs($row['actual_price']), false);		  
		$goods_list[$row['goods_id']]['subtotal_number']                =  intval($row['subtotal_number']);
		$goods_list[$row['goods_id']]['formated_subtotal_amount']       =  price_format(abs($row['subtotal_amount']), false);
		$goods_list[$row['goods_id']]['subtotal_number_in']             =  intval($row['subtotal_number_in']);
		$goods_list[$row['goods_id']]['subtotal_number_loss']           =  intval($row['subtotal_number_loss']);
		$goods_list[$row['goods_id']]['formated_subtotal_loss_amount']  =  price_format($row['subtotal_loss_amount'], false);				
	}
	$sql = "SELECT og.*,g.goods_name,g.goods_sn,IFNULL(c.color_name,'默认') color_name,IFNULL(s.size_name,'默认') size_name,
	       IFNULL(b.brand_name, '') AS brand_name FROM " . $GLOBALS['os']->table('scm_'.$str_type.'_goods') . 
	       ' og LEFT JOIN ' . $GLOBALS['os']->table('goods') . ' g ON og.goods_id=g.goods_id LEFT JOIN ' . 
	       $GLOBALS['os']->table('color') . " c ON og.color_id=c.color_id LEFT JOIN " . $GLOBALS['os']->table('size') . 
	       ' s ON og.size_id=s.size_id LEFT JOIN ' . $GLOBALS['os']->table('brand') . ' b ON  g.brand_id=b.brand_id ' . 
	       ' WHERE og.order_id=' . intval($order_id) . ' ORDER BY og.rec_id DESC';
	$result = $GLOBALS['db']->query($sql);
	while ($row = $GLOBALS['db']->fetchRow($result)) {
		if(isset($goods_list[$row['goods_id']]) && is_array($goods_list[$row['goods_id']])){		
			$goods_list[$row['goods_id']]['sub_list'][$row['rec_id']]                                   =  $row;
			$goods_list[$row['goods_id']]['sub_list'][$row['rec_id']]['short_goods_name']               =  sub_str($row['goods_name'], 16);
			$goods_list[$row['goods_id']]['sub_list'][$row['rec_id']]['goods_sn']                       =  sub_str($row['goods_sn'], 0);
			$goods_list[$row['goods_id']]['sub_list'][$row['rec_id']]['formated_actual_price']          =  price_format(abs($row['actual_price']), false);		  
			$goods_list[$row['goods_id']]['sub_list'][$row['rec_id']]['subtotal_number']                =  intval($row['goods_number']);
			$goods_list[$row['goods_id']]['sub_list'][$row['rec_id']]['formated_subtotal_amount']       =  price_format(abs($row['actual_amount']), false);	
		    $goods_list[$row['goods_id']]['sub_list'][$row['rec_id']]['goods_attr']                     =  '颜色:' . $row['color_name'] . '&nbsp;&nbsp;尺码:' . $row['size_name'];
		    $goods_list[$row['goods_id']]['sub_list'][$row['rec_id']]['subtotal_number_in']             =  intval($row['goods_number_inventory']);
		    $goods_list[$row['goods_id']]['sub_list'][$row['rec_id']]['subtotal_number_loss']           =  intval($row['goods_number_loss']);
			$goods_list[$row['goods_id']]['sub_list'][$row['rec_id']]['formated_subtotal_loss_amount']  =  price_format($row['loss_amount'], false);	
		}
	}

	return $goods_list;	
}

function scm_loss_order_list(){
    $result = get_filter();
    if ($result === false)
    {
        /* 初始化分页参数 */
        $filter = array();
        $filter['sort_by']    = empty($_REQUEST['sort_by']) ? 'order_id' : trim($_REQUEST['sort_by']);
        $filter['sort_order'] = empty($_REQUEST['sort_order']) ? 'DESC' : trim($_REQUEST['sort_order']);
        $filter['order_sn']   = empty($_REQUEST['order_sn']) ? '' : trim($_REQUEST['order_sn']);
        $filter['status']     = (!is_numeric($_REQUEST['status']) || $_REQUEST['status']<0) ? -1 : intval($_REQUEST['status']);
        $filter['start_add_time'] = empty($_REQUEST['start_add_time']) ? '' : (strpos($_REQUEST['start_add_time'], '-') > 0 ?  local_strtotime($_REQUEST['start_add_time']) : $_REQUEST['start_add_time']);
        $filter['end_add_time'] = empty($_REQUEST['end_add_time']) ? '' : (strpos($_REQUEST['end_add_time'], '-') > 0 ?  local_strtotime($_REQUEST['end_add_time']) : $_REQUEST['end_add_time']);	

        $where = 'WHERE 1 ';
        if ($filter['order_sn'])
        {
            $where .= " AND o.order_sn LIKE '%" . mysql_like_quote($filter['order_sn']) . "%'";
        }
        if($filter['status']>=0){
        	$where .= " AND o.order_status=$filter[status]";
        } 
        if ($filter['start_add_time'])
        {
            $where .= " AND o.add_time >= '$filter[start_add_time]'";
        }
        if ($filter['end_add_time'])
        {
            $where .= " AND o.add_time <= '$filter[end_add_time]'";
        }                   
        /* 查询记录总数，计算分页数 */
   		$sql = "SELECT COUNT(*) FROM " . $GLOBALS['os']->table('scm_loss_order') . " o " . $where;
        $filter['record_count'] = $GLOBALS['db']->getOne($sql);
        $filter = page_and_size($filter);

        /* 查询记录 */
        $sql = "SELECT o.* FROM " . $GLOBALS['os']->table('scm_loss_order') . " o " . $where .
   		       " ORDER BY $filter[sort_by] $filter[sort_order]";
        set_filter($filter, $sql);
    }
    else
    {
        $sql    = $result['sql'];
        $filter = $result['filter'];
    }
    $res = $GLOBALS['db']->selectLimit($sql, $filter['page_size'], $filter['start']);

    $arr = array();
    while ($row = $GLOBALS['db']->fetchRow($res))
    {      
		$row['status']  				    = scm_order_status('loss', $row['order_status']);
      	$row['formated_order_amount']	    = price_format(abs($row['order_amount']), false);
      	$row['formated_order_amount_loss']	= price_format($row['order_amount_loss'], false);
      	$row['formated_add_time']           = local_date('Y-m-d', $row['add_time']);
        $arr[] = $row;
    }
    return array('item' => $arr, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);	
}

function scm_rectify_order_list(){
    $result = get_filter();
    if ($result === false)
    {
        /* 初始化分页参数 */
        $filter = array();
        $filter['sort_by']    		= empty($_REQUEST['sort_by']) ? 'order_id' : trim($_REQUEST['sort_by']);
        $filter['sort_order'] 		= empty($_REQUEST['sort_order']) ? 'DESC' : trim($_REQUEST['sort_order']);
        $filter['order_sn'] 		= empty($_REQUEST['order_sn']) ? '' : trim($_REQUEST['order_sn']);
        $filter['status']     		= (!is_numeric($_REQUEST['status']) || $_REQUEST['status']<0) ? -1 : intval($_REQUEST['status']);
        $filter['start_add_time']	= empty($_REQUEST['start_add_time']) ? '' : (strpos($_REQUEST['start_add_time'], '-') > 0 ?  local_strtotime($_REQUEST['start_add_time']) : $_REQUEST['start_add_time']);
        $filter['end_add_time'] 	= empty($_REQUEST['end_add_time']) ? '' : (strpos($_REQUEST['end_add_time'], '-') > 0 ?  local_strtotime($_REQUEST['end_add_time']) : $_REQUEST['end_add_time']);	

        $where = 'WHERE 1 ';
        if ($filter['order_sn'])
        {
            $where .= " AND o.order_sn LIKE '%" . mysql_like_quote($filter['order_sn']) . "%'";
        }
        if($filter['status']>=0){
        	$where .= " AND o.order_status=$filter[status]";
        } 
        if ($filter['start_add_time'])
        {
            $where .= " AND o.add_time >= '$filter[start_add_time]'";
        }
        if ($filter['end_add_time'])
        {
            $where .= " AND o.add_time <= '$filter[end_add_time]'";
        }                   
        /* 查询记录总数，计算分页数 */
   		$sql = "SELECT COUNT(*) FROM " . $GLOBALS['os']->table('scm_rectify_order') . " o " . $where;
        $filter['record_count'] = $GLOBALS['db']->getOne($sql);
        $filter = page_and_size($filter);

        /* 查询记录 */
        $sql = "SELECT o.* FROM " . $GLOBALS['os']->table('scm_rectify_order') . " o " . $where .
   		       " ORDER BY $filter[sort_by] $filter[sort_order]";
        set_filter($filter, $sql);
    }
    else
    {
        $sql    = $result['sql'];
        $filter = $result['filter'];
    }
    $res = $GLOBALS['db']->selectLimit($sql, $filter['page_size'], $filter['start']);

    $arr = array();
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
		$row['status']  				    = scm_order_status('rectify', $row['order_status']);
		$row['formated_discount']  		    = sprintf('%s', $row['discount']);
      	$row['formated_order_amount']	    = price_format(abs($row['order_amount']), false);
      	$row['formated_order_amount_loss']	= price_format($row['order_amount_loss'], false);
      	$row['formated_add_time']           = local_date('Y-m-d', $row['add_time']);
        $arr[] = $row;
    }
    return array('item' => $arr, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);		
}

function scm_rectify_order_info($order_id, $order_sn = ''){
    /* 计算订单各种费用之和的语句 */
    $order_id = intval($order_id);
    if ($order_id > 0)
    {
        $sql = "SELECT o.* FROM " . $GLOBALS['os']->table('scm_rectify_order') . " o WHERE o.order_id = '$order_id'";	
    }
    else
    {
        $sql = "SELECT o.* FROM " . $GLOBALS['os']->table('scm_rectify_order') . " o WHERE o.order_sn = '$order_sn'";	
    }
    $order = $GLOBALS['db']->getRow($sql);

    /* 格式化金额字段 */
    if ($order)
    {		
        $order['depot_name']                  = ' 默认 ';
        $order['seat_name']                   = ' 默认 ';
     	$order['formated_add_time']           = local_date('Y-m-d', $order['add_time']);     
        $order['formated_order_amount']       = price_format(abs($order['order_amount']), false);
        $order['formated_order_amount_loss']  = price_format($order['order_amount_loss'], false);
		$order['status']                      = scm_order_status('rectify', $order['order_status']);		
    }

    return $order;		
}

function scm_rectify_goods($order_id){
	static $goods_list = array();
	$sql = "SELECT og.*,SUM(og.goods_number) subtotal_number,SUM(og.actual_amount) subtotal_amount," . 
	       "SUM(og.goods_number_loss) subtotal_number_loss,SUM(og.loss_amount) subtotal_loss_amount," . 
		   "g.goods_name,g.goods_sn FROM " . $GLOBALS['os']->table('scm_rectify_goods') . " og LEFT JOIN " . 
		   $GLOBALS['os']->table('goods') . " g ON og.goods_id=g.goods_id WHERE og.order_id=" . intval($order_id) . 
	       " GROUP BY og.goods_id ORDER BY rec_id DESC";
	$res = $GLOBALS['db']->query($sql);
	while ($row = $GLOBALS['db']->fetchRow($res)) {
		$goods_list[$row['goods_id']]['order_id']                       =  $row['order_id'];
		$goods_list[$row['goods_id']]['goods_id']                       =  $row['goods_id'];
		$goods_list[$row['goods_id']]['goods_name']                     =  sub_str($row['goods_name'], 0);
		$goods_list[$row['goods_id']]['goods_sn']                       =  sub_str($row['goods_sn'], 0);
		$goods_list[$row['goods_id']]['formated_norm_price']            =  price_format(abs($row['norm_price']), false);		
		$goods_list[$row['goods_id']]['formated_discount']              =  sprintf('%s', $row['discount']);
		$goods_list[$row['goods_id']]['formated_actual_price']          =  price_format(abs($row['actual_price']), false);		  
		$goods_list[$row['goods_id']]['subtotal_number']                =  intval($row['subtotal_number']);
		$goods_list[$row['goods_id']]['formated_subtotal_amount']       =  price_format(abs($row['subtotal_amount']), false);	
		$goods_list[$row['goods_id']]['subtotal_number_loss']           =  intval($row['subtotal_number_loss']);
		$goods_list[$row['goods_id']]['formated_subtotal_loss_amount']  =  price_format($row['subtotal_loss_amount'], false);		      		
	}
	return $goods_list;
}

function status_alter_to_balance($order_type, $order_id){
    if(!in_array($order_type, array(1, 2))) return false;	
    $tb = sprintf('scm_%s_order', ($order_type==2) ? 'return' : 'enter');
    $all_amount = $GLOBALS['db']->getOne("SELECT order_amount FROM " . $GLOBALS['os']->table($tb) . " WHERE order_id='$order_id'");
    $payed_amount = $GLOBALS['db']->getOne("SELECT SUM(d.pay_amount) FROM " . $GLOBALS['os']->table('scm_balance_detail') . " d JOIN " . 
                    $GLOBALS['os']->table('scm_balance_order') . " o ON d.order_id=o.order_id WHERE o.order_status=1 AND " . 
                    " d.order_type='$order_type' AND d.from_order_id='$order_id'");    							
    if(abs($payed_amount) >= $all_amount){
    	$order_status = ($order_type==2) ? 3 : 3;
		$GLOBALS['db']->query("UPDATE " . $GLOBALS['os']->table($tb) . " SET order_status='$order_status' WHERE order_id='$order_id'");	
    }	
}

function get_pays_list(){
	static $pays_list = array();
	$result = $GLOBALS['db']->query("SELECT * FROM ".$GLOBALS['os']->table('scm_payment')." WHERE is_show=1");
	while ($row = $GLOBALS['db']->fetchRow($result)) {
		$pays_list[$row['pay_id']] = $row['pay_name'];
	}
	return $pays_list;
}
    

function query_balance_order(){
    $result = get_filter();
    if ($result === false)
    {
        /* 初始化分页参数 */
        $filter = array();
        $filter['sort_by']    = empty($_REQUEST['sort_by']) ? 'order_id' : trim($_REQUEST['sort_by']);
        $filter['sort_order'] = empty($_REQUEST['sort_order']) ? 'DESC' : trim($_REQUEST['sort_order']);
        $filter['supplier_id']   = empty($_REQUEST['supplier_id']) ? 0 : intval($_REQUEST['supplier_id']);
        $filter['start_add_time']      = empty($_REQUEST['start_add_time']) ? '' : (strpos($_REQUEST['start_add_time'], '-') > 0 ?  local_strtotime($_REQUEST['start_add_time']) : $_REQUEST['start_add_time']);
        $filter['end_add_time']        = empty($_REQUEST['end_add_time']) ? '' : (strpos($_REQUEST['end_add_time'], '-') > 0 ?  local_strtotime($_REQUEST['end_add_time']) : $_REQUEST['end_add_time']);
        
        $where = '';
        if ($_REQUEST['is_clear']=='yes') {
        	$where .= " AND o.order_id=0";
        }
        if ($filter['supplier_id'])
        {
            $where .= " AND o.supplier_id='$filter[supplier_id]'";
        }
        if ($filter['start_add_time'])
        {
            $where .= " AND o.add_time >= '$filter[start_add_time]'";
        }
        if ($filter['end_add_time'])
        {
            $where .= " AND o.add_time <= '$filter[end_add_time]'";
        }
                   
        /* 查询记录总数，计算分页数 */
   		$sql = "SELECT COUNT(*) FROM " . $GLOBALS['os']->table('scm_enter_order') . " o LEFT JOIN " . 
   			   $GLOBALS['os']->table('supplier') . " s ON o.supplier_id=s.supplier_id WHERE o.order_status=2 " . $where;
        $filter['record_count'] = $GLOBALS['db']->getOne($sql);
   		$sql = "SELECT COUNT(*) FROM " . $GLOBALS['os']->table('scm_return_order') . " o LEFT JOIN " . 
   			   $GLOBALS['os']->table('supplier') . " s ON o.supplier_id=s.supplier_id WHERE o.order_status=1 " . $where;
        $filter['record_count'] += $GLOBALS['db']->getOne($sql);
        $filter = page_and_size($filter);

        /* 查询记录 */
        $sql = "SELECT o.order_id,o.order_sn,o.goods_number,o.order_amount,1 order_type,o.add_time,s.supplier_name FROM " . 
               $GLOBALS['os']->table('scm_enter_order') . " o LEFT JOIN " . $GLOBALS['os']->table('supplier') . 
               " s ON o.supplier_id=s.supplier_id WHERE o.order_status=2 $where UNION SELECT o.order_id,o.order_sn," .                         "concat('-',o.goods_number),concat('-',o.order_amount),2 order_type,o.add_time,s.supplier_name FROM " .                         $GLOBALS['os']->table('scm_return_order') . " o LEFT JOIN " . $GLOBALS['os']->table('supplier') . 
               " s ON o.supplier_id=s.supplier_id WHERE o.order_status=1 $where ORDER BY $filter[sort_by] $filter[sort_order]";
        set_filter($filter, $sql);
    }
    else
    {
        $sql    = $result['sql'];
        $filter = $result['filter'];
    }
    $res = $GLOBALS['db']->query($sql);

    $arr = array();
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
    	$payed_amount = $GLOBALS['db']->getOne("SELECT SUM(pay_amount) FROM " . $GLOBALS['os']->table('scm_balance_detail') . 
    										" WHERE order_type=" . intval($row['order_type']) . " AND from_order_id=" . intval($row['order_id']));
        if(abs($payed_amount) < abs($row['order_amount'])){
        	$row['short_supplier_name']	        = sub_str($row['supplier_name'], 10);
	      	$row['formated_order_amount']	    = price_format($row['order_amount'], false);
	      	$row['formated_payed_amount']	    = price_format($payed_amount, false);
	      	$row['formated_add_time']           = local_date('Y-m-d', $row['add_time']);
	        $arr[] = $row;
        }
    }
    return array('item' => $arr, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);	
}

function get_balance_amount($order_id){
	$sql = "SELECT SUM(pay_amount) FROM ".$GLOBALS['os']->table('scm_balance_detail')." WHERE order_id=".intval($order_id);
	$balance_amount = $GLOBALS['db']->getOne($sql);
	return floatval($balance_amount);
}


function scm_balance_order_info($order_id){
    /* 计算订单各种费用之和的语句 */
    $order_id = intval($order_id);
    if ($order_id > 0)
    {
        $sql = "SELECT o.*,s.supplier_name,p.pay_name FROM " . $GLOBALS['os']->table('scm_balance_order') . 
               " o LEFT JOIN " . $GLOBALS['os']->table('supplier') . " s ON o.supplier_id=s.supplier_id " . 
               " LEFT JOIN " . $GLOBALS['os']->table('scm_payment') . " p ON o.pay_type=p.pay_id " .	
               " WHERE o.order_id = '$order_id'";	
    }
    else
    {
        $sql = "SELECT o.*,s.supplier_name,p.pay_name FROM " . $GLOBALS['os']->table('scm_balance_order') . 
        	   " o LEFT JOIN " . $GLOBALS['os']->table('supplier') . " s ON o.supplier_id=s.supplier_id " .
        	   " LEFT JOIN " . $GLOBALS['os']->table('scm_payment') . " p ON o.pay_type=p.pay_id " .	
               " WHERE o.order_sn = '$order_sn'";	
    }
    $order = $GLOBALS['db']->getRow($sql);

    /* 格式化金额字段 */
    if ($order)
    {
    	if($order['order_type']==1){
    		$enter_order = $GLOBALS['db']->getRow("SELECT order_id, order_sn FROM " . $GLOBALS['os']->table('scm_enter_order') . 
    		                                      " WHERE order_id=$order[from_order_id]");
    		if($enter_order){
    			$order['enter_order_id']     = $enter_order['order_id'];
    			$order['enter_order_sn']     = $enter_order['order_sn'];
    		}
    	}elseif($order['order_type']==2){
    		$return_order = $GLOBALS['db']->getRow("SELECT order_id, order_sn FROM " . $GLOBALS['os']->table('scm_return_order') . 
    		                                      " WHERE order_id=$order[from_order_id]"); 
    		if($return_order){
    			$order['return_order_id']     = $return_order['order_id'];
    			$order['return_order_sn']     = $return_order['order_sn'];    			
    		}   		
    	}
    	$order['short_supplier_name']     = sub_str($order['supplier_name'], 10);
    	$order['short_pay_name']   	  	  = sub_str($order['pay_name'], 10);
     	$order['formated_add_time']       = local_date('Y-m-d', $order['add_time']);       
     	$order['formated_deliver_time']   = local_date('Y-m-d', $order['deliver_time']);       
        $order['formated_order_amount']   = price_format($order['order_amount'], false);
        $order['formated_pay_amount']     = price_format($order['pay_amount'], false);
        $order['formated_surplus_amount'] = price_format(abs($order['surplus_amount']), false);
		$order['status']                  = scm_order_status('balance', $order['order_status']);
    }

    return $order;	
}

function scm_balance_order_list(){
    $result = get_filter();
    if ($result === false)
    {
        /* 初始化分页参数 */
        $filter = array();
        $filter['sort_by']          = empty($_REQUEST['sort_by']) ? 'order_id' : trim($_REQUEST['sort_by']);
        $filter['sort_order']       = empty($_REQUEST['sort_order']) ? 'DESC' : trim($_REQUEST['sort_order']);
        $filter['order_sn'] 		= empty($_REQUEST['order_sn']) ? '' : trim($_REQUEST['order_sn']);
        if (!empty($_GET['is_ajax']) && $_GET['is_ajax'] == 1)
        {
            $_REQUEST['supplier_name'] = json_str_iconv($_REQUEST['supplier_name']);
        }
        $filter['supplier_name']    = empty($_REQUEST['supplier_name']) ? '' : trim($_REQUEST['supplier_name']);
        $filter['status']     		= (!is_numeric($_REQUEST['status']) || $_REQUEST['status']<0) ? -1 : intval($_REQUEST['status']);
        $filter['balance_type']     = (!is_numeric($_REQUEST['balance_type']) || $_REQUEST['balance_type']<0) ? -1 : intval($_REQUEST['balance_type']);
        $filter['pay_type']     	= (!is_numeric($_REQUEST['pay_type']) || $_REQUEST['pay_type']<0) ? -1 : intval($_REQUEST['pay_type']);
        $filter['start_add_time']      = empty($_REQUEST['start_add_time']) ? '' : (strpos($_REQUEST['start_add_time'], '-') > 0 ?  local_strtotime($_REQUEST['start_add_time']) : $_REQUEST['start_add_time']);
        $filter['end_add_time']        = empty($_REQUEST['end_add_time']) ? '' : (strpos($_REQUEST['end_add_time'], '-') > 0 ?  local_strtotime($_REQUEST['end_add_time']) : $_REQUEST['end_add_time']);
        $filter['start_deliver_time']  = empty($_REQUEST['start_deliver_time']) ? '' : (strpos($_REQUEST['start_deliver_time'], '-') > 0 ?  local_strtotime($_REQUEST['start_deliver_time']) : $_REQUEST['start_deliver_time']);
        $filter['end_deliver_time']    = empty($_REQUEST['end_deliver_time']) ? '' : (strpos($_REQUEST['end_deliver_time'], '-') > 0 ?  local_strtotime($_REQUEST['end_deliver_time']) : $_REQUEST['end_deliver_time']);
                
        $where = 'WHERE 1 ';
        if ($filter['supplier_name'])
        {
            $where .= " AND s.supplier_name LIKE '%" . mysql_like_quote($filter['supplier_name']) . "%'";
        }  
        if($filter['status']>=0){
        	$where .= " AND o.order_status='$filter[status]'";
        }  
        if($filter['balance_type']>=0){
        	$where .= " AND o.balance_type='$filter[balance_type]'";
        }  
        if($filter['pay_type']>=0){
        	$where .= " AND o.pay_type='$filter[pay_type]'";
        }  
        if ($filter['start_add_time'])
        {
            $where .= " AND o.add_time >= '$filter[start_add_time]'";
        }
        if ($filter['end_add_time'])
        {
            $where .= " AND o.add_time <= '$filter[end_add_time]'";
        }
        if ($filter['start_deliver_time'])
        {
            $where .= " AND o.deliver_time >= '$filter[start_deliver_time]'";
        }
        if ($filter['end_deliver_time'])
        {
            $where .= " AND o.deliver_time <= '$filter[end_deliver_time]'";
        }  
                   
        /* 查询记录总数，计算分页数 */
   		$sql = "SELECT COUNT(*) FROM " . $GLOBALS['os']->table('scm_balance_order') . " o LEFT JOIN " . 
   		       $GLOBALS['os']->table('supplier') . " s ON o.supplier_id=s.supplier_id LEFT JOIN " . 
   		       $GLOBALS['os']->table('scm_payment') . " p ON o.pay_type=p.pay_id " . $where;

        $filter['record_count'] = $GLOBALS['db']->getOne($sql);
        $filter = page_and_size($filter);

        /* 查询记录 */
        $sql = "SELECT o.*,s.supplier_name,p.pay_name FROM " . $GLOBALS['os']->table('scm_balance_order') . 
               " o LEFT JOIN " . $GLOBALS['os']->table('supplier') . " s ON o.supplier_id=s.supplier_id LEFT JOIN " . 
   		       $GLOBALS['os']->table('scm_payment') . " p ON o.pay_type=p.pay_id " .  
               $where . " ORDER BY $filter[sort_by] $filter[sort_order]";
        set_filter($filter, $sql);
    }
    else
    {
        $sql    = $result['sql'];
        $filter = $result['filter'];
    }
    $res = $GLOBALS['db']->selectLimit($sql, $filter['page_size'], $filter['start']);

    $arr = array();
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
    	$row['short_supplier_name']         = sub_str($row['supplier_name'], 10);
      	$row['status'] 					    = scm_order_status('balance', $row['order_status']);
      	$row['formated_order_amount']	    = price_format($row['order_amount'], false);
      	$row['formated_pay_amount']	        = price_format($row['pay_amount'], false);
      	$row['formated_surplus_amount']	    = price_format(abs($row['surplus_amount']), false);
      	$row['formated_deliver_time']       = local_date('Y-m-d', $row['deliver_time']);
      	$row['formated_add_time']           = local_date('Y-m-d', $row['add_time']);
      	$row['short_pay_name']              = sub_str($row['pay_name'], 10);
        $arr[] = $row;
    }
    return array('item' => $arr, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);		
}

function scm_balance_detail($order_id){
	$sql = "SELECT d.*,o.order_sn FROM " . $GLOBALS['os']->table('scm_balance_detail') . " d LEFT JOIN " . 
	       $GLOBALS['os']->table('scm_enter_order') . " o ON d.from_order_id=o.order_id WHERE d.order_id=" . 
	       intval($order_id) . " AND d.order_type=1 UNION SELECT d.*,o.order_sn FROM " . 
	       $GLOBALS['os']->table('scm_balance_detail') . " d LEFT JOIN " . $GLOBALS['os']->table('scm_return_order'). 
	       " o ON d.from_order_id=o.order_id WHERE d.order_id=" . intval($order_id) . 
	       " AND d.order_type=2 ORDER BY rec_id DESC";
	$res = $GLOBALS['db']->query($sql);
	$order_list = array();
	while ($row = $GLOBALS['db']->fetchRow($res)) {
		$row['formated_order_amount']   =  price_format($row['order_amount']);	
		$row['formated_payed_amount']   =  price_format($row['payed_amount']);		
		$row['formated_pay_amount']     =  price_format($row['pay_amount']);			
		$row['formated_surplus_amount'] =  price_format($row['surplus_amount']);	
		$row['formated_add_time']       =  local_date('Y-m-d', $row['add_time']);			
		$order_list[]   		        =  $row;      		
	}
	return $order_list;		
}

function scm_payment_list(){
   $result = get_filter();
    if ($result === false)
    {
        /* 初始化分页参数 */
        $filter = array();
        $filter['sort_by']    = empty($_REQUEST['sort_by']) ? 'pay_id' : trim($_REQUEST['sort_by']);
        $filter['sort_order'] = empty($_REQUEST['sort_order']) ? 'DESC' : trim($_REQUEST['sort_order']);
      	if (!empty($_GET['is_ajax']) && $_GET['is_ajax'] == 1)
        {
            $_REQUEST['pay_name'] = json_str_iconv($_REQUEST['pay_name']);
        }
        $filter['pay_name']   = empty($_REQUEST['pay_name']) ? '' : trim($_REQUEST['pay_name']);
        $filter['pay_code']   = empty($_REQUEST['pay_code']) ? '' : trim($_REQUEST['pay_code']);
        $where = 'WHERE 1 ';
        if ($filter['pay_name'])
        {
            $where .= " AND pay_name LIKE '%" . mysql_like_quote($filter['pay_name']) . "%'";
        }

        if ($filter['pay_code'])
        {
            $where .= " AND pay_code LIKE '%" . mysql_like_quote($filter['pay_code']) . "%'";
        }
        /* 查询记录总数，计算分页数 */
   		$sql = "SELECT COUNT(*) FROM " . $GLOBALS['os']->table('scm_payment') . $where;

        $filter['record_count'] = $GLOBALS['db']->getOne($sql);
        $filter = page_and_size($filter);

        /* 查询记录 */
        $sql = "SELECT * FROM " . $GLOBALS['os']->table('scm_payment') . $where . " ORDER BY $filter[sort_by] $filter[sort_order]";
        set_filter($filter, $sql);
    }
    else
    {
        $sql    = $result['sql'];
        $filter = $result['filter'];
    }
    $res = $GLOBALS['db']->selectLimit($sql, $filter['page_size'], $filter['start']);

    $arr = array();
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        $arr[] = $row;
    }
    return array('item' => $arr, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);
}












function scm_check_order_list(){
    $result = get_filter();
    if ($result === false)
    {
        /* 初始化分页参数 */
        $filter = array();
        $filter['sort_by']    = empty($_REQUEST['sort_by']) ? 'order_id' : trim($_REQUEST['sort_by']);
        $filter['sort_order'] = empty($_REQUEST['sort_order']) ? 'DESC' : trim($_REQUEST['sort_order']);
        $filter['order_sn'] = empty($_REQUEST['order_sn']) ? '' : trim($_REQUEST['order_sn']);
        $filter['status']     = (!is_numeric($_REQUEST['status']) || $_REQUEST['status']<0) ? -1 : intval($_REQUEST['status']);
        $filter['start_add_time'] = empty($_REQUEST['start_add_time']) ? '' : (strpos($_REQUEST['start_add_time'], '-') > 0 ?  local_strtotime($_REQUEST['start_add_time']) : $_REQUEST['start_add_time']);
        $filter['end_add_time'] = empty($_REQUEST['end_add_time']) ? '' : (strpos($_REQUEST['end_add_time'], '-') > 0 ?  local_strtotime($_REQUEST['end_add_time']) : $_REQUEST['end_add_time']);	

        $where = 'WHERE 1 ';
        if ($filter['order_sn'])
        {
            $where .= " AND o.order_sn LIKE '%" . mysql_like_quote($filter['order_sn']) . "%'";
        }
        if($filter['status']>=0){
        	$where .= " AND o.order_status=$filter[status]";
        } 
        if ($filter['start_add_time'])
        {
            $where .= " AND o.add_time >= '$filter[start_add_time]'";
        }
        if ($filter['end_add_time'])
        {
            $where .= " AND o.add_time <= '$filter[end_add_time]'";
        }                   
        /* 查询记录总数，计算分页数 */
   		$sql = "SELECT COUNT(*) FROM " . $GLOBALS['os']->table('scm_check_order') . " o " . $where;
        $filter['record_count'] = $GLOBALS['db']->getOne($sql);
        $filter = page_and_size($filter);

        /* 查询记录 */
        $sql = "SELECT o.* FROM " . $GLOBALS['os']->table('scm_check_order') . " o " . $where .
   		       " ORDER BY $filter[sort_by] $filter[sort_order]";
        set_filter($filter, $sql);
    }
    else
    {
        $sql    = $result['sql'];
        $filter = $result['filter'];
    }
    $res = $GLOBALS['db']->selectLimit($sql, $filter['page_size'], $filter['start']);

    $arr = array();
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
		$row['status']  				    = scm_order_status('check', $row['order_status']);
      	$row['formated_order_amount']	    = price_format(abs($row['order_amount']), false);      	
      	$row['formated_add_time']           = local_date('Y-m-d', $row['add_time']);
        $arr[] = $row;
    }
    return array('item' => $arr, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);	
}

function scm_check_order_info($order_id, $order_sn = ''){
  /* 计算订单各种费用之和的语句 */
    $order_id = intval($order_id);
    if ($order_id > 0)
    {
        $sql = "SELECT o.* FROM " . $GLOBALS['os']->table('scm_check_order') . " o WHERE o.order_id = '$order_id'";	
    }
    else
    {
        $sql = "SELECT o.* FROM " . $GLOBALS['os']->table('scm_check_order') . " o WHERE o.order_sn = '$order_sn'";	
    }
    $order = $GLOBALS['db']->getRow($sql);

    /* 格式化金额字段 */
    if ($order)
    {		
        $order['depot_name']                  = ' 默认 ';
        $order['seat_name']                   = ' 默认 ';
     	$order['formated_add_time']           = local_date('Y-m-d', $order['add_time']);     
        $order['formated_order_amount']       = price_format(abs($order['order_amount']), false);
		$order['status']                      = scm_order_status('check', $order['order_status']);
    }

    return $order;	
}

function temp_order_goods($str_type, $order_id){
	$sql = "SELECT og.*,g.goods_name,g.goods_sn,c.color_code,c.color_name,s.size_code,s.size_name FROM " . 
	       $GLOBALS['os']->table('scm_'.$str_type.'_goods') . " og LEFT JOIN " . $GLOBALS['os']->table('goods') . 
	       " g ON og.goods_id=g.goods_id LEFT JOIN " . $GLOBALS['os']->table('color') . " c ON og.color_id=c.color_id LEFT JOIN " . 
	       $GLOBALS['os']->table('size') . " s ON og.size_id=s.size_id WHERE og.order_id=".intval($order_id);
	$temp_goods = $GLOBALS['db']->getAll($sql);
	return $temp_goods;		 
}


function get_order_goods_list(){
    $result = get_filter();
    if ($result === false)
    {
        /* 初始化分页参数 */
        $filter = array();
        $filter['sort_by']          = empty($_REQUEST['sort_by']) ? 'goods_id' : trim($_REQUEST['sort_by']);
        $filter['sort_order']       = empty($_REQUEST['sort_order']) ? 'DESC' : trim($_REQUEST['sort_order']);
        $filter['type']             = empty($_REQUEST['type']) ? '' : trim($_REQUEST['type']);	
        $filter['order_id']         = empty($_REQUEST['order_id']) ? 0 : intval($_REQUEST['order_id']);
        
        $ext_sql = " WHERE g.is_delete=0 AND og.order_id='$filter[order_id]'";

        /* 查询记录总数，计算分页数 */
        $sql = "SELECT COUNT(*) FROM " . $GLOBALS['os']->table('scm_'.$filter['type'].'_goods') . " og JOIN " . 
               $GLOBALS['os']->table('goods') . " g ON og.goods_id=g.goods_id " . $ext_sql;
        $filter['record_count'] = $GLOBALS['db']->getOne($sql);
        $filter['page_size']    = $filter['record_count'];
        $filter['page_count']   = 1;
        $filter['start']        = 0;

        /* 查询记录 */
        $sql = "SELECT og.actual_price,og.goods_number,og.actual_amount,g.goods_id,g.goods_name,g.goods_sn,c.color_id,c.color_name," . 
               "c.color_code,s.size_id,s.size_name,s.size_code FROM " . $GLOBALS['os']->table('scm_'.$filter['type'].'_goods') . 
               " og JOIN " . $GLOBALS['os']->table('goods') . " g ON og.goods_id=g.goods_id LEFT JOIN " . $GLOBALS['os']->table('color') . 
               " c ON og.color_id=c.color_id LEFT JOIN " . $GLOBALS['os']->table('size') . " s ON og.size_id=s.size_id " . $ext_sql . 
               " ORDER BY $filter[sort_by] $filter[sort_order]";
        set_filter($filter, $sql);
    }
    else
    {
        $sql    = $result['sql'];
        $filter = $result['filter'];
    }
    $res = $GLOBALS['db']->selectLimit($sql, $filter['page_size'], $filter['start']);

    $arr_goods    = array();
	$goods_specs  = array();
	$goods_list   = array();
	$arr_total    = array();
	
    while ($row = $GLOBALS['db']->fetchRow($res))
    { 
    	$goods_list[$row['goods_id']] = $row;
        $arr_goods[] = $row;
        
 		$arr_total[$row['goods_id']]['total_number'] += $row['goods_number'];        
        $arr_total[$row['goods_id']]['total_amount'] += $row['actual_amount'];
    }

    foreach($arr_goods as $row){
    	$goods_specs[$row['goods_id']][$row['color_id']] = array('color_id'=>$row['color_id'],'color_code'=>$row['color_code'],'color_name'=>$row['color_name']);
    }
    
	foreach($arr_goods as $row){
  		$goods_specs[$row['goods_id']][$row['color_id']]['size_specs'][$row['size_id']] = array('size_id'=>$row['size_id'],'size_code'=>$row['size_code'],'size_name'=>$row['size_name'],'goods_number'=>$row['goods_number']);
	}
	
    $arr = array();
    foreach($goods_list as $g){
    	$g['specs']             = !empty($goods_specs[$g['goods_id']]) ? $goods_specs[$g['goods_id']] : 0;
    	$g['short_goods_name']  = sub_str($g['goods_name'], 20);
    	$g['total_number']      = !empty($arr_total[$g['goods_id']]) ? intval($arr_total[$g['goods_id']]['total_number']) : 0;
    	$g['total_amount']      = !empty($arr_total[$g['goods_id']]) ? floatval($arr_total[$g['goods_id']]['total_amount']) : 0;
        $arr[] = $g;
    }
    return array('goods' => $arr, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);
}

/**
 *
 *
 * @access  public
 * @param
 *
 * @return void
 */
function utf82u2($str)
{
    $len = strlen($str);
    $start = 0;
    $result = '';

    if ($len == 0)
    {
        return $result;
    }

    while ($start < $len)
    {
        $num = ord($str{$start});
        if ($num < 127)
        {
            $result .= chr($num) . chr($num >> 8);
            $start += 1;
        }
        else
        {
            if ($num < 192)
            {
                /* 无效字节 */
                $start ++;
            }
            elseif ($num < 224)
            {
                if ($start + 1 <  $len)
                {
                    $num = (ord($str{$start}) & 0x3f) << 6;
                    $num += ord($str{$start+1}) & 0x3f;
                    $result .=   chr($num & 0xff) . chr($num >> 8) ;
                }
                $start += 2;
            }
            elseif ($num < 240)
            {
                if ($start + 2 <  $len)
                {
                    $num = (ord($str{$start}) & 0x1f) << 12;
                    $num += (ord($str{$start+1}) & 0x3f) << 6;
                    $num += ord($str{$start+2}) & 0x3f;

                    $result .=   chr($num & 0xff) . chr($num >> 8) ;
                }
                $start += 3;
            }
            elseif ($num < 248)
            {

                if ($start + 3 <  $len)
                {
                    $num = (ord($str{$start}) & 0x0f) << 18;
                    $num += (ord($str{$start+1}) & 0x3f) << 12;
                    $num += (ord($str{$start+2}) & 0x3f) << 6;
                    $num += ord($str{$start+3}) & 0x3f;
                    $result .= chr($num & 0xff) . chr($num >> 8) . chr($num >>16);
                }
                $start += 4;
            }
            elseif ($num < 252)
            {
                if ($start + 4 <  $len)
                {
                    /* 不做处理 */
                }
                $start += 5;
            }
            else
            {
                if ($start + 5 <  $len)
                {
                    /* 不做处理 */
                }
                $start += 6;
            }
        }

    }

    return $result;
}
?>